...

View Full Version : jQuery dynamic input field ids



An Enigman
03-08-2011, 11:50 AM
Hi,

I'm trying to find a way to create a dynamic functionality that gives the user an option to fill out more of the same forms by clicking the add form button. I've got the cloning bit working but I need to find a way to dynamically assign the input field id numbers so they increment accordingly. So for example something like this for the ids: input1, input2, etc..

My existing code is:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);

var newElem = $('#form' + num).clone().attr('id', 'form' + newNum);
newElem.attr('id', 'form' + newNum).attr('name', 'form' + newNum);
$('#form' + num).after(newElem);
$('#btnDel').attr('disabled','');

if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});

$('#btnDel').click(function() {
var num = $('.clonedInput').length;

$('#input' + num).remove();
$('#btnAdd').attr('disabled','');

if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});

$('#btnDel').attr('disabled','disabled');
});
</script>
</head>

<body>


<div id="form1" style="margin-bottom:4px;" class="clonedInput" style="width: 950px;">
<table cellpadding='0' cellspacing='0' border='0' style="width: 950px;">
<tr>
<td style="width:70px;">
<b>First Name:</b>
</td>
<td id="test" style="width: 200px;">
<input type="text" id="fname1" name="fname1" style="width:200px;"/>
</td>
<td style="width: 20px;">

</td>
<td>
<b>Last Name:</b>
</td>
<td>
<input type="text" name="lname1" id="lname1" style="width:513px;" />
</td>
</tr>
<tr>
<td>
<b>Job Number: </b>
</td>
<td style="width:200px;">
<input type="text" name="job1" id="job1" style="width:200px;" />
</td>
<td style="width: 20px;">

</td>
<td>
<b>Role:</b>
</td>
<td>
<input type="text" name="role1" id="role1" style="width:513px;" />
</td>
</tr>
</table>


</div>



<div>
<input type="button" id="btnAdd" value="add another form" />
<input type="button" id="btnDel" value="remove previous form" />
</div>


</body>
</html>


The problem I'm having is that this only dynamically adds the number increment for the div id. I want all the input fields to have that same number increment functionality so that when the information is stored in a MySQL database, I can differentiate between the info.

Can someone please assist me in finding a solution to this problem?

Thanks.

An Enigman
03-09-2011, 01:29 AM
anyone?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum