2011-03-17 93 views
0

我有一個包含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

回答

0
$("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

0

給一個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

0

排序。問題在於,通過改變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事件對輸入做了工作。有可能是一個更優雅的方式做到這一點,但它的工作...