注册在表单中点击了哪个图像


Register which image has been clicked in form

我在HTML文档中有多个图像,我希望它们在单击时呈现唯一的值(以某种可检索的方式)。我试过把它们作为表单元素,像这样:

<form id="myform" method="post" action="">
    <input type="hidden" name="action" value="submit" />
    <div class="flex-item"><input type="image" name="submit" value="alt1" alt="alt1" src="images/<?php echo $data[$counter] ?>"></div>
    <div class="flex-item"><input type="image" name="submit" value="alt2" alt="alt2" src="images/<?php echo $data[$counter+1] ?>"></div>
</form>

在本例中,我想用PHP访问POST数据,如下所示:

if (isset($_POST['action'])) {
    echo '<br />The ' . $_POST['submit'] . ' button was pressed';
}

但这不起作用,因为它是image输入类型,似乎无法发送数据。我曾尝试使用一个按钮与图像作为背景,但这种方式我将不得不调整每个图像的大小,使其适合按钮(我想避免,因为我有很多图像)。

我知道我可以用Javascript将图像用作提交按钮,但正如我所说的,关于哪个图像被点击的信息也需要以某种方式可用。有什么最好的解决方案吗?

HTML/CSS - Only way.

设置隐藏单选按钮的CSS:

.hidden {
    display: none !important;
}

在表单中,使用单选按钮来跟踪选择的图像。将图像放入标签中,标签为"for"相关的单选按钮。一定要在PHP中把你想要的信息放在单选按钮的value属性中:

<form method="post" name="myForm">
    <div>
        <input type="radio" name="image" value="image1" id="image1" class="hidden">
        <label for="image1"><img src="path-to-your-image.jpg"></label>
    </div>
    <div>
        <input type="radio" name="image" value="image2" id="image2" class="hidden">
        <label for="image2"><img src="path-to-your-other-image.jpg"></label>
    </div>
    <div>
        <input type="submit" name="save" value="Save Image Selection">
    </div>
</form>

如果你需要表单在他们点击图片时提交,那么添加这段javascript:

<script>
    // No-conflict-mode-safe document ready function (waits until page is loaded to run, which ensures radio buttons are available to bind to)
    jQuery(function($) {
        // Hide / suppress the submit button
        $('input[type="submit"]').closest('div').hide();
        // Bind to change event for all radio buttons
        $('input[type="radio"]').on('change', function() {
            // Submit the form ("this" refers to the radio button)
            $(this).closest('form').submit();
        });
    });
</script>
然后,当你提交这个表单时,在你的PHP中你可以这样做:
$image = $_POST[ 'image' ]; // 'image' is the name of the radio buttons
var_dump( $image );
// Will result in "image1" or "image2", etc - whatever "value" you assigned to the radio buttons

当您使用代码时,您可以在$_POST对象中获得submit参数(因为按钮的属性name)。该值将是value属性。

你可以这样检查:

<form id="myform" method="post" action="">
    <input type="hidden" name="action" value="submit" />
    <div class="flex-item"><input type="image" name="submit" value="alt1" alt="alt1" src="images/img1"></div>
    <div class="flex-item"><input type="image" name="submit" value="alt2" alt="alt2" src="images/img2"></div>
</form>
<?php
if (isset($_POST['submit'])) {
    if ($_POST['submit'] == 'alt1') {
        echo 'alt1 clicked';
            // First button clicked 
    }
    else {
        echo 'alt2 clicked';
            // second button clicked
    }
}
?>