Jquery Validate which image clicked
I have a form with 5 icons and I want to validate which one is clicked. I thought to add a hidden text box and write a rule which checks the value of it. This works on form submit, but I need the error message to be cleared on clicking the correct image. At the moment, the validation is not fired when the text value is changed by javascript. Any better way of doing this?
<form name="frmExperiment" id="frmExperiment" action="" method="post">
<img src="btn1.png" width="75" height="75" alt="continue" title="continue" onclick="frmExperiment.txtIconG.value=1" />
<img src="btn2.png" width="75" height="74" alt="information" title="information" onclick="frmExperiment.txtIconG.value=2" />
<img src="btn3.png" width="75" height="82" alt="refresh" title="refresh" onclick="frmExperiment.txtIconG.value=3" />
<img src="btn4.png" width="75" height="75" alt="home" title="home" onclick="frmExperiment.txtIconG.value=4" />
<img src="btn6.png" width="75" height="77" alt="stop" title="st开发者_如何学编程op" onclick="frmExperiment.txtIconG.value=5" />
<input type="text" name="txtIconG" id="txtIconG" />
</form>
and
$.validator.addMethod("iconmatch", function (value, element) {
return value==1;
},
"That isn't the continue button"
);
$("img").bind("click", function(){
var whichImg = $(this).attr("title");
if( whichImg == "continue" ) {
// do stuff or submit the form
} else {
var txt = "That isnt the continue button! You've clicked the "+ whichImg + " button!";
$("#txtIconG").val( txt );
}
return false;
});
Give an id to each img and on click of each id you do what ever you want . I hope id of img shud work other wise put a span or div for each img and give id to them
$('#target').click(function() {
alert('Handler for .click() called.');
});
Sorted. The problem was that changing the value by js onclick doesn't fire the validation. So, I removed the onclicks and in jQuery added:
$('#frmExperiment img').click(function(){
$('#txtIconG').val($(this).attr('src'));
$('#txtIconG').keyup();
});
and in the custom rule:
$.validator.addMethod("iconmatch", function (value, element) {
return value=='btn1.png';
},
"That isn't the continue button"
);
So, firing the keyup event on the input did the job. There may be a more elegant way of doing this, but it's working...
精彩评论