Friday, December 31, 2010

JQuery: Validate all the controls in the rows of a table

Validating all the controls of each row of a TABLE element can be done at clientside using jQuery.






<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery Page</title>
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<style type="text/css">
.mandatory
{
border: solid 1px red;
}
</style>
<script type="text/javascript">
function CallThis()
{
var mandatorys = $('#tableid').find('.mandatory');
var allFieldsComplete = true;
mandatorys.each(function(index) {
if (this.value.length == 0) {
$(this).addClass('mandatory');
allFieldsComplete = false;
} else {
//alert(this.value);
$(this).removeClass('mandatory');
}
});
if(!allFieldsComplete){
$('#dispMsg').html('Mandatory fields to be entered');
}
return allFieldsComplete;
}
</script>

</head>
<body>
<table id="tableid" border="1" class="tableid">
<tr> <td>
<input type="text" class="mandatory" />
</td> <td>
<input type="text" class="mandatory" />
</td> </tr>
<tr> <td>
<input type="text" class="mandatory" />
</td>
<td><input type="text" class="mandatory" />
</td> </tr> </table>
<div id="dispMsg" style="color:Red;"></div>
<input type="button" class="txtbox" value="Validate" onclick="javascript:CallThis();" />
</body>
</html>

No comments: