Jquery验证点击了哪个图像

问题描述:

我有一个包含5个图标的窗体,我想验证哪个窗体被点击。我想添加一个隐藏文本框并写出一个检查它的值的规则。这适用于表单提交,但是我需要在单击正确图像时清除错误消息。目前,当文本值被javascript改变时,验证不会被触发。还有更好的方法吗?Jquery验证点击了哪个图像

<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="stop" onclick="frmExperiment.txtIconG.value=5" /> 
<input type="text" name="txtIconG" id="txtIconG" /> 
</form> 

$.validator.addMethod("iconmatch", function (value, element) { 
return value==1; 
}, 
"That isn't the continue button" 
); 
+0

不应该是'(值== 1)'? – mattsven 2011-03-17 19:57:49

+0

返回值== 1将返回true或false。 – 2011-03-17 20:05:10

$("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; 
}); 
+0

鲍勃,谢谢,我如何将它与验证绑定? – rubhadubh 2011-03-17 20:09:09

+0

现在验证你是否点击了右键,队友!你甚至不需要你的html标签中的onclick! – 2011-03-17 20:15:43

+1

为简洁起见,我剪下了这个表格 - 有一堆其他表单元素在提交之前需要验证。这就是为什么我想使用自定义规则执行此操作的原因 – rubhadubh 2011-03-17 20:23:32

给一个ID,每个IMG和每个ID的点击你做你什么都想要。 我希望IMG的ID shud工作的其他明智的把SPAN或DIV每个IMG并给ID他们

$('#target').click(function() { 
    alert('Handler for .click() called.'); 
}); 
+0

我可以通过'$('#frmExperiment img')检测到哪个img被点击了。click(function(){alert($(this).attr('src'));});'但是我不知道如何将其绑定到自定义规则 – rubhadubh 2011-03-17 20:11:03

排序。问题在于,通过改变js onclick的值不会触发验证。所以,我删除了onclicks和jQuery中补充说:

$('#frmExperiment img').click(function(){ 
    $('#txtIconG').val($(this).attr('src')); 
    $('#txtIconG').keyup(); 
}); 

,并在自定义规则:

$.validator.addMethod("iconmatch", function (value, element) { 
    return value=='btn1.png'; 
}, 
    "That isn't the continue button" 
); 

因此,发射KeyUp事件对输入做了工作。有可能是一个更优雅的方式做到这一点,但它的工作...