I my requirement form is generated dynamically. there are number of fields
<tr>
<td >Coding Guidelines</td>
<td align="center">
<select name="SELECT_TASK_1" id="SELECT_TASK_1">
<option value="">Select</option>
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</td>
<td align="center"><input type="text" size="10" name="COMP_DATE_1"开发者_StackOverflow社区></td>
<td align="left"> <textarea name="COMMENT_TASK_1" id="COMMENT_TASK_1"
cols="45" rows="4"></textarea><span id="COMMENT_ERROR_1" > </span>
</td>
</tr>
there are number of TR generated base on DB rows. I want apply jquery validation on the combination of select No value and Comment field.
That means if select is No then comment is mandatory field.
Please help how to apply validation using Jquery validation plugin
Here is a solution (though not very optimised):
<table>
<tr>
<td>
<select>
<option value="0">select</option>
<option value="1">yes</option>
<option value="2">no</option>
</select>
</td>
<td>
<textarea cols="10" rows="3"></textarea>
<span id="COMMENT_ERROR_1"></span>
</td>
</tr>
<tr>
<td>
<select>
<option value="0">select</option>
<option value="1">yes</option>
<option value="2">no</option>
</select>
</td>
<td>
<textarea cols="10" rows="3"></textarea>
<span id="COMMENT_ERROR_1"></span>
</td>
</tr>
</table>
<input type="button" id="validate" value="validate"/>
<script type="text/javascript">
$(function(){
$("#validate").click(function(){
$.each($("select"),function(){
var n=$("option:selected",this).text();
if(n=="no")
{
var $txt=$("textarea",$(this).closest("tr"));
if($txt.text()=="")
{
var $sp=$txt.parent().find("span");
$sp.text("Enter comment");
}
else
{
var $sp=$txt.parent().find("span");
$sp.text("Enter comment");
}
}
});
});
});
</script>
Perhaps you can attach a handler to the submit form button:
$(#form-id).submit(function(){
var valid = true;
if($('#SELECT_TASK_1').val() == "N" && $('#COMMENT_TASK_1').val() == '')
valid = false;
return valid
});
For selecting all selects:
var selects = $('#form-id').find('select');
for(var i = 0; i < selects.length; i++){
if(selects[i].val() == 'N'){
if(area is empty)
valid = false;
}
}
精彩评论