Jump to content

Dynamically add form elements via Javascript in a table format


holy24

Recommended Posts

Hi, I am trying to create a form in a table format whereby there are 1 row and 3 columns(1 field in each column). There will be a "Add" button, and if user click on the button, another row will appear with the 3 fields. Below are the codes that I have wrote:- When user 1st view, they can see the table with header, 1 row with 3 fields, an add button- However, if user click on "Add" button, the 2nd row appear outside the table format. Can someone advise me how to make it appear inside the same table just after the 1st row? Thanks. <script type="text/javascript"> function addInput(divName){ <?php include 'connectdb.php'; $result=mysql_query("SELECT * FROM table_name"); ?> var newdiv1 = document.createElement('div1'); var newdiv2 = document.createElement('div2'); var newdiv3 = document.createElement('div3'); newdiv1.innerHTML = "<input type='text' name='name[]'>"; newdiv2.innerHTML = "<select name='company[]'><option value=''></option><?php while ($row=mysql_fetch_array($result) { ? ><option value=<?php echo $row['company'] ?>><?php echo $row['company'] ?></option><?php } ?></select>"; newdiv3.innerHTML = "<input type='text' name='address[]'><br>"; document.getElementById(divName).appendChild(newdiv1); document.getElementById(divName).appendChild(newdiv2); document.getElementById(divName).appendChild(newdiv3);}</script> <?php include 'connectdb.php'; $result=mysql_query("SELECT * FROM table_name");?> <div id="dynamicInput"> <table align="center" border="1"> <tr> <td><b>Name</b></td> <td><b>Company</b></td> <td><b>Address</b></td> </tr> <tr> <td><input type="text" name="name[]"></td> <td> <select name="company[]"> <option value=""></option> <?php while ($row=mysql_fetch_array($result)){ ?> <option value=<?php echo $row["company"] ?>><?php echo $row["company"] ?></option> <?php } ?> </select> </td> <td><input type="text" name="address[]"></td> </tr> </table> <p align=center><input type="button" value="Add" onClick="addInput('dynamicInput')"></p> </div>

Link to comment
Share on other sites

Hi, The following codes now correctly shown a table with 1 row and 3 fields. When user click on "add", another row will appear. My question is: If user entered 3 rows of data, how can I capture all these data and insert into a database? I tried echoing and the outcome is always getting the last record. Can someone please kindly advice on this? Thanks. Example:formName | Company | AddressUser1 | Company 1 | Address 1User2 | Company 2 | Address 2User3 | Company 3 | Address 3 database Name | Company | AddressUser1 | Company 1 | Address 1User2 | Company 2 | Address 2User3 | Company 3 | Address 3 ------------------------------------------------------------------------------------------------<script type="text/javascript"> $(function(){ var newRowNum = 0; $('#addnew').click(function(){ newRowNum += 1; var addRow = $(this).parent().parent(); var newRow = addRow.clone(); $('input', addRow).val(''); $('select', addRow).val(''); $('td:first-child', newRow).html(""); $('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>'); $('input', newRow).each(function(i){ var newID = newRowNum + '_' + i; $(this).attr('id',newID).attr('name',newID); }); $('select', newRow).each(function(i){ var newID = newRowNum + '_' + i; $(this).attr('id',newID).attr('name',newID); }); addRow.before(newRow); $('a.remove', newRow).click(function(){ $(this).parent().parent().remove(); return false; }); return false; });}); </script> <?php include 'connectdb.php'; $result=mysql_query("SELECT * FROM table_name");?> <table align="center" border="1"> <tr> <td></td> <td>Name</td> <td>Company</td> <td>Address</td> <td></td> </tr> <tr> <td><a id="addnew" href="">Add</a></td> <td><input name="name[]" type="text"></td> <td> <select name="company[]"> <option value=""></option> <?php while($row=mysql_fetch_array($result)){ ?> <option value="<?php echo $row['company']; ?>"><?php echo $row['company']; ?></option> <?php } ?> </select> </td> <td><input name="address[]" type="text"></td> <td></td> </tr> </table> -------------------------------------------------------------------------------------------------

Link to comment
Share on other sites

That Javascript code is completely different, you're not writing this yourself are you? It was better the first time, just missing a few things. The first code is much more readable than the jQuery code. You need to give the elements names like you had in the first code, where the name ends with brackets. The new code isn't doing that, it's giving each element a unique name. If you had it like you did in the first code then in PHP you could get, for example, $_POST['name'], and it would be an array of all of the name inputs. $_POST['company'] would be an array of all of the company values, etc.

Link to comment
Share on other sites

Hi, I have re-write using my 1st code and now the layout looks fine and able to insert into the database. Now, I am trying to prompt user to fill in the field if it is blank. For the default first row, I am able to do so. But I am not sure why the appendchild fields are not prompting the user when field is empty upon submitting? Can kindly advice on this? Thanks. ---------------------------------------------<script type="text/javascript"> function validateForm(){var x=document.forms["form"]["name[]"].value;var y=document.forms["form"]["company[]"].value;var z=document.forms["form"]["address[]"].value; if (x=="" || x==null){alert("Please fill in name field!");return false;}else if (y=="" || y==null){alert("Please fill in company field!");return false;}else if (z=="" || z==null){alert("Please fill in address field!");return false;}} function addInput(){<?phpinclude 'connectdb.php';$result=mysql_query("SELECT * FROM table_name");?> var tbl = document.getElementById('tblAddress');var lastRow = tbl.rows.length;var row = tbl.insertRow(lastRow); var cell0 = row.insertCell(0);var el = document.createElement('input');el.type='text';el.name='name[]';cell0.appendChild(el); var cell1 = row.insertCell(1);var selector = document.createElement('select');selector.name='company[]';cell1.appendChild(selector); var option = document.createElement('option');option.value = '';option.appendChild(document.createTextNode(''));selector.appendChild(option); <?php while($row=mysql_fetch_array($result)){?>var option = document.createElement('option');option.value = '<?php echo $row["company"];?>';option.appendChild(document.createTextNode('<?php echo $row["company"];?>'));selector.appendChild(option);<?php } ?> var cell2 = row.insertCell(2);var el = document.createElement('input');el.type ='text';el.name='address[]';cell2.appendChild(el); el = document.createElement('input');el.type ='button';el.value='Remove';el.onmouseup=function(){ Remove(this); }cell2.appendChild(el);}function Remove(obj){while (obj.parentNode){if (obj.nodeName.toUpperCase()=='TR'){break;}obj=obj.parentNode;}obj.parentNode.removeChild(obj);return;}</script> <html><body> <form name="form" method="post" action="xxx.php" onsubmit="return validateForm()"> <?phpinclude 'connectdb.php';$result=mysql_query("SELECT * FROM table_name");?> <table align="center" border="1" id="tblAddress"> <tr><td><b>Name</b></td><td><b>Company</b></td><td><b>Address</b></td></tr> <tr><td><input type="text" name="name[]"></td><td><select name="company[]"><option value=""></option><?php while ($row=mysql_fetch_array($result)){ ?><option value='<?php echo $row["company"] ?>'><?php echo $row["company"]; ?></option><?php } ?></select></td><td><input type="text" name="address[]"></td></tr> </table><p align="center"><input type="button" value="Add" onClick="addInput();"></p></form></body></html>

Link to comment
Share on other sites

  • 2 weeks later...

This line: var x=document.forms["form"]["name[]"].value; does not get a list of all inputs, only a single one. You can use a function like document.getElementsByTagName to loop through all inputs, check the name and value of each one, and show the error messages.

Link to comment
Share on other sites

  • 2 weeks later...
This line: var x=document.forms["form"]["name[]"].value; does not get a list of all inputs, only a single one. You can use a function like document.getElementsByTagName to loop through all inputs, check the name and value of each one, and show the error messages.
Hi, I have been reading this function document.getElementsByTagName but still do not understand how it work. I have tried implementing it on my existing code but it seems not working. Can kindly explain on this? Thanks. function validateForm(){var x=document.getElementsByTagName('name');var y=document.getElementsByTagName('company');var z=document.getElementsByTagName('address');if (x=="" || x==null){alert("Please fill in name field!");return false;}else if (y=="" || y==null){alert("Please fill in company field!");return false;}else if (z=="" || z==null){alert("Please fill in address field!");return false;}} <tr><name>< td><input type="text" name="name[]"></td></name><company>< td>< select name="company[]">< option value=""></option>< ?php while ($row=mysql_fetch_array($result)){ ?>< option value='<?php echo $row["company"] ?>'><?php echo $row["company"]; ?></option>< ?php } ?>< /select>< /td></company> <address>< td><input type="text" name="address[]"></td></address>< /tr>
Link to comment
Share on other sites

document.getElementsByTagName(); is used to get a specific HTML element like 'p' or 'div'; returns a collection of the specified tag name. There are no 'company' and 'name' html tags that I am aware of. There is a 'address' tag though. If you thought getElementsByTagName mean't getting an element when an elements name attribute is set to a specified name like <input type="text" name="address" />, then no, that's not what getElementsByTagName does. Maybe you were thinking of document.getElementsByName. http://www.w3schools...tsbytagname.asp http://www.w3schools...mentsbyname.asp JSG meant something like...

var inputs = document.getElementsByTagName('input'); for(var i = 0; i < inputs.length; i++) {	 if(inputs[i].name == "address" && inputs[i].value == NULL)	 {		  alert("Please fill in Address field.");		  return false;	 } 	 etc...	 }

Edited by Don E
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...