Saturday, January 1, 2011

JQuery: Add, Deete Rows, Validate the controls of added rows of a Table

What if the new rows with controls has to be added dynamically and deleted on button clicks and those controls have to be validated before submitting to the server. JQuery is the easiest way to add/remove at the client side dynamically.

Have a sneak peek here.


Look at the code here





<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 requiredFields = $('#tableid').find('.requiredField');
var allFieldsComplete = true;
requiredFields.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">
<thead>
<tr>
<td bgcolor="#f1f1f1">Header 1</td>
<td bgcolor="#f1f1f1">Header 2</td>
</tr>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField2" /></td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField2" /></td>
</tr>
<tr>
<td><input type="text" class="requiredField" /></td>
<td><input type="text" class="requiredField" /></td>
</tr>
</tbody>
</table>
<div id="dispMsg" style="color:Red;"></div>
<input type="button" class="txtbox" value="Validate" onclick="javascript:CallThis();" />
<input type="button" id="btnTest" value="Add"/>
<input type="button" id="btnTest2" value="Remove"/>
</body>
<script type="text/javascript">

$('#btnTest').click(function() {
$('#tableid > tbody:last').append('<tr><td><input type="text" id="txt1" class="requiredField"/> </td><td>yyy</td></tr>');
});
$('#btnTest2').click(function() {
$('#tableid > tbody:last tr:last').remove();
});
</script>
</html>

No comments: