pass image id into form and submit with jQuery
I have a few images on a page. Each image has an id value assigned. I need to get image id, pass it into a form and submit that form when the image is clicked.
<IMG SRC="img1.gif" id="var1">
<IMG SRC="img2.gif" id="var2"&开发者_开发知识库gt;
<form method="post" id="myForm" action="thisPage.php">
<input type="hidden" name="myID">
</form>
How do I pass the value from image into form?
Now, I do know I can use ajax with jQuery, but in this case I actually need to submit to this page and reload it after submitting.
still you can use jQuery without ajax.
$(function() {
$('img').click(function() {
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});
});
see demo. http://jsfiddle.net/gwgCH/3/
<script type="text/javascript">
function setImage(imgid) {
document.getElementById('formImage').value = imgid;
document.getElementById('myForm').submit();
}
</script>
<IMG SRC="img1.gif" id="var1" onclick="setImage('var1');" />
<IMG SRC="img2.gif" id="var2" onclick="setImage('var2');" />
<form method="post" id="myForm" action="thisPage.php">
<input type="hidden" id="formImage" />
</form>
A javascript solution
<IMG SRC="img1.gif" id="var1" onclick="setid(this.id)">
function setid(id)
{
document.getElementById('myID').value=id;
document.forms[0].submit();
}
精彩评论