我在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的提交按钮,但正如我所说,关于哪个图像被点击的信息也需要以某种方式提供。关于最佳解决方案的任何想法?
答案 0 :(得分:1)
HTML / CSS - 唯一的方式。
设置CSS以隐藏单选按钮:
.hidden {
display: none !important;
}
在表单中,使用单选按钮跟踪选择的图像。将图像放在“用于”相关单选按钮的标签内。请务必在单选按钮的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
答案 1 :(得分:0)
当您使用代码时,submit
对象中的name
参数(因为按钮属性为$_POST
)。该值将为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
}
}
?>