JavaScript - Need Help In In Creating Dynamic Fields
hi i am newbie to js please help me like a newbie thanks.
i want to make a form. the form will have three text fields and with two buttons. what i want with this form is when the user enters the first three fields and if he wants to add more then he will click on add more button and on the same page three more fields will appear below the first three fields. the user will then enter these three fields then if he wants to add more then he will click on add more button. so three more fields will appear below the first six fields. user will enter these fields. he will be allowed to enter upto eight or less than eight times. once he finishes with this then he will click the second button to insert this data into db. Similar TutorialsI am using a script that duplicates a fieldset and an onBlur event that updates a sub total when you enter a value into 3 fields in the set but I am having one glitch that I can not figure out and would appreciate any insight you can provide. Here is the trouble: The duplication of the fieldset works great. I have another script which is creating a sum ("sum") of the fields named "unitPrice" in the original fieldset. When I duplicate the fieldset that has the new "unitPrice" fields they do not get calculated into that sum. I am sure the "unitPrice" fields are being renamed in the new fieldset but what name would I use and how do I write it into the calculation so that the sub total ("sum") is updated with all of the "unitPrice" fields? Thanks for your help. Code: <!DOC HTML> <html> <head> <title> Untitled </title> <script type="text/javascript"> function insertAfter(newElement, targetElement) { var parent = targetElement.parentNode; if (parent.lastChild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } // Suffix + Counter var suffix = ':'; var counter = 1; // Clone nearest parent fieldset function cloneMe(a) { // Increment counter counter++; // Find nearest parent fieldset var original = a.parentNode; while (original.nodeName.toLowerCase() != 'fieldset') { original = original.parentNode; } var duplicate = original.cloneNode(true); // Label - For and ID var newLabel = duplicate.getElementsByTagName('label'); for (var i = 0; i < newLabel.length; i++) { var labelFor = newLabel[i].htmlFor if (labelFor) { oldFor = labelFor.indexOf(suffix) == -1 ? labelFor : labelFor.substring(0, labelFor.indexOf(suffix)); newLabel[i].htmlFor = oldFor + suffix + counter; } var labelId = newLabel[i].id if (labelId) { oldId = labelId.indexOf(suffix) == -1 ? labelId : labelId.substring(0, labelId.indexOf(suffix)); newLabel[i].id = oldId + suffix + counter; } } // Input - Name + ID var newInput = duplicate.getElementsByTagName('input'); for (var i = 0; i < newInput.length; i++) { var inputName = newInput[i].name if (inputName) { oldName = inputName.indexOf(suffix) == -1 ? inputName : inputName.substring(0, inputName.indexOf(suffix)); newInput[i].name = oldName + suffix + counter; } var inputId = newInput[i].id if (inputId) { oldId = inputId.indexOf(suffix) == -1 ? inputId : inputId.substring(0, inputId.indexOf(suffix)); newInput[i].id = oldId + suffix + counter; } } // Select - Name + ID var newSelect = duplicate.getElementsByTagName('select'); for (var i = 0; i < newSelect.length; i++) { var selectName = newSelect[i].name if (selectName) { oldName = selectName.indexOf(suffix) == -1 ? selectName : selectName.substring(0, selectName.indexOf(suffix)); newSelect[i].name = oldName + suffix + counter; } var selectId = newSelect[i].id if (selectId) { oldId = selectId.indexOf(suffix) == -1 ? selectId : selectId.substring(0, selectId.indexOf(suffix)); newSelect[i].id = oldId + suffix + counter; } } // Textarea - Name + ID var newTextarea = duplicate.getElementsByTagName('textarea'); for (var i = 0; i < newTextarea.length; i++) { var textareaName = newTextarea[i].name if (textareaName) { oldName = textareaName.indexOf(suffix) == -1 ? textareaName : textareaName.substring(0, textareaName.indexOf(suffix)); newTextarea[i].name = oldName + suffix + counter; } var textareaId = newTextarea[i].id if (textareaId) { oldId = textareaId.indexOf(suffix) == -1 ? textareaId : textareaId.substring(0, textareaId.indexOf(suffix)); newTextarea[i].id = oldId + suffix + counter; } } duplicate.className = 'duplicate'; insertAfter(duplicate, original); } // Delete nearest parent fieldset function deleteMe(a) { var duplicate = a.parentNode; while (duplicate.nodeName.toLowerCase() != 'fieldset') { duplicate = duplicate.parentNode; } duplicate.parentNode.removeChild(duplicate); } </script> <script> function myFunction(){ var the_fields = document.getElementsByName("unitPrice"); var the_sum = 0; for (var i=0; i<the_fields.length; i++){ if (the_fields[i].value != "" && !isNaN(the_fields[i].value)) { the_sum += Number(the_fields[i].value); } } document.repairform.sum.value = (the_sum.toFixed(2)); } </script> <SCRIPT LANGUAGE="JavaScript"> function CalculateTotal() { firstnumber = document.repairform.sum.value/100; secondnumber = document.repairform.tax.value; total = (firstnumber * secondnumber -0) + (document.repairform.sum.value -0); document.repairform.grandTotal.value = total.toFixed(2) ; } </SCRIPT> <script> function checkDecimal(obj, objStr){ var objNumber; if(isNaN(objStr) && objStr!=''){ alert('Value entered is not numeric'); objNumber = '0.00'; } else if(objStr==''){ objNumber = '0.00'; } else if(objStr.indexOf('.')!=-1){ if(((objStr.length) - (objStr.indexOf('.')))>3){ objStr = objStr.substr(0,((objStr.indexOf('.'))+3)); } if(objStr.indexOf('.')==0){ objStr = '0' + objStr; } var sLen = objStr.length; var TChar = objStr.substr(sLen-3,3); if(TChar.indexOf('.')==0){ objNumber = objStr; } else if(TChar.indexOf('.')==1){ objNumber = objStr + '0'; } else if(TChar.indexOf('.')==2){ objNumber = objStr + '00'; } } else{ objNumber = objStr + '.00'; } obj.value = objNumber; } </script> </head> <body> <form id="item_details" name="repairform" method="post" action="#" onSubmit="return false;"> <h2>Contact Information</h2> <fieldset> <table cellspacing="10"> <tr> <td> <label for="name"> Name: </label> </td> <td> <input type="text" id="name" name="name" /> </td> <td> <label for="form-phone"> Phone: </label> </td> <td> <input id="form-phone" type="tel" required> </td> </tr> <tr> <td> <label for="form-date"> Date: </label> </td> <td> <input id="form-date" type="date"required> </td> <td> <label for="form-datewanted"> Date Wanted </label> </td> <td> <input id="form-datewanted" type="date" required> </td> </tr> <tr> <td> <label for="form-address"> Address </label> </td> <td> <input id="form-address" type="text"> </td> </tr> </table> </fieldset> <h2>Vehicle Information</h2> <fieldset> <table cellspacing="10"> <tr> <td> <label for="form-ymc"> Year-Model-Color</label> </td> <td> <input id="form-ymc" type="text" required> </td> <td> <label for="form-make">MAKE</label> </td> <td> <input id="form-make" type="text"> </td> </tr> <tr> <td><label for="form-bodytype">BODY TYPE</label> </td> <td> <input id="form-bodytype" type="text"> </td> <td> <label for="form-unitno">UNIT NO.</label> </td> <td> <input id="form-unitno" type="text"> </td> </tr> <tr> <td> <label for="form-serialno">SERIAL NO.</label> </td> <td> <input id="form-serialno" type="text"> </td> <td> <label for="form-motorno">MOTOR NO.</label> </td> <td> <input id="form-motorno" type="text"> </td> </tr> <tr> <td> <label for="form-mileage">MILEAGE</label> </td> <td> <input id="form-mileage" type="text"> </td> <td> </td> <td> </td> </tr> </table> </fieldset> <h2>Repair Estimate</h2> <fieldset> <span class="tab"> <a href="#" onClick="cloneMe(this); return false;" class="cloneMe" title="Add">+</a> <a href="#" onClick="deleteMe(this); return false;" class="deleteMe" title="Delete">x</a> </span> <table cellspacing="10"> <tr> <td> <label for="repair_replace">Repair/Replace</label> </td> <td class="mainText"> <input class="radio" name="repair_replace" type="radio" value="Repair" />Repair<br> <input class="radio" name="repair_replace" type="radio" value="Replace" />Replace </td> <td> <label for="form-description">Description: </label> </td> <td > <textarea id="form-description" name="form-description" cols="5" rows="5" ></textarea> </td> </tr> <tr> <td> <label>PARTS AND MATERIALS </label> </td> <td><input name="unitPrice" value="" id="parts" onBlur="myFunction(); checkDecimal(this,this.value)" onFocus="this.focus();" class="dollar" /> </td> <td> <label>LABOR </label> </td> <td ><input name="unitPrice" value="" id="labor" type="text" onblur="myFunction(); checkDecimal(this,this.value)" class="dollar"/> </td> </tr> <tr> <td> <label>REFINISHING </label> </td> <td><input name="unitPrice" id="refinishing" type="text" onBlur="myFunction(); checkDecimal(this,this.value)" class="dollar"/> </td> <td> </td> <td > </td> </tr> </table> </fieldset> <h2>Price Estimate</h2> <fieldset> <table cellspacing="10"> <tr> <td><label>SUB TOTAL </label> </td> <td><input type="text" name="sum" class="dollar" readonly/> </td> <td> <label>Tax %</label> </td> <td> <input class="tax" type="text" name="tax" onBlur="CalculateTotal()" /> </td> </tr> <tr> <td> <label>GRAND TOTAL </label> </td> <td> <input type="text" name="grandTotal" class="dollar" readonly/> </td> <td> </td> <td > <p> <input type="submit" value="Send Estimate" onClick="myFunction()"> </p> </td> </tr> </table> </fieldset> <p> <input type="submit" value="Submit" class="button" /><input type="reset" value="Reset" class="button" /> </p> </form> </body> </html> i have a script which i found on the internet. i modify that script according to my needs. what is in that script is there are three form fields with two buttons. one button is "Give me more fields" clicking on this button will give you more fields. and second button is submit so the data goes to server side and will be added to db. the problem is when i click give me more fields it gives me three more fields which is right but when i fill all these fields and click submit button it adds to the db but the data in the first three fields adds in the one row and the other three fields data adds in separate row which is not fine for me. so how can i do this so all the data will be added to only one row. here is js code Code: var counter = 0; //Start a counter. Yes, at 0 function add_phone() { counter++; // I find it easier to start the incrementing of the counter here. var newFields = document.getElementById('addQualification').cloneNode(true); newFields.id = ''; newFields.style.display = 'block'; var newField = newFields.childNodes; for (var i=0;i<newField.length;i++) { var theName = newField[i].name if (theName) newField[i].name = theName + counter; // This will change the 'name' field by adding an auto incrementing number at the end. This is important. } var insertHere = document.getElementById('addQualification'); // Inside the getElementById brackets is the name of the div class you will use. insertHere.parentNode.insertBefore(newFields,insertHere); } here is my form Code: <form name="addAQualification" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> <fieldset> <div id="phone"> Degree: <input type="text" name="degree_0" value="" /><br> CGPA/Grade: <input type="text" name="cgpa_0" value="" /><br> Institute: <input type="text" name="institute_0" value="" /><br> </div> <div id="addQualification" style="display: none;"> Degree: <input type="text" name="degree_" value="" /><br> CGPA/Grade: <input type="text" name="cgpa_" value="" /><br> Institute: <input type="text" name="institute_" value="" /><br> </div> <input type="button" id="add_phone()" onclick="add_phone()" value="Give me more fields!" /><br> <input type="submit" name="submit" value="submit" /> </fieldset> </form> here is my php Code: <?php if(isset($_POST['submit'])) //This checks to make sure submit was clicked { echo "You clicked submit!<br>"; echo "Here is your data<br>"; echo "<br>"; if ($_POST['cgpa_0']) //This checks that the proper field has data { $continue = FALSE; $i = 0; while ($continue == FALSE) { if (isset($_POST['degree_'.$i])) //This looks for an entry after 0 and increments { echo $_POST['degree_'.$i] . " = " . $_POST['cgpa_'.$i] . "<br>"; //Echoing the data $degree1 = $_POST['degree_'.$i]; $cgpa1 = $_POST['cgpa_'.$i]; $institute1 = $_POST['institute_'.$i]; $db = mysql_connect("localhost"); mysql_select_db("test", $db); $query = "INSERT INTO cv ( degree1, cgpa1, institute1 ) VALUES ( '$degree1', '$cgpa1', '$institute1' )"; $result = mysql_query($query); //The four lines above is the example on how the data would be put into a MySQL database. It's not used here } else { $continue = TRUE; } $i++; } } } ?> hi guys kindly assist in this i have the code below used to generate additional dynamic fields how can i save data entered in mysql??? <HTML> <HEAD> <TITLE>New Task</TITLE> <link rel="stylesheet" href="style1.css" type="text/css"/> <meta http-equiv="Content-Script-Type" content="text/javascript"> <SCRIPT language="javascript"> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = rowCount + 1; newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes); switch(newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } }catch(e) { alert(e); } } </SCRIPT> </HEAD> <BODY> <br> <br> <h2>INPUT NEW TASK</h2> <table border="1" width="100%"> <tr> <td> <fieldset> <legend></legend> <table border="0" width="100%"> <tr> <td>User:</td> <td><input type="text" size="20" name=""disabled></td> <td>Start Date:</td> <td><input type="text" size="20"></td> </tr> <tr> <td>Client name:</td> <td><select name=""></select></td> <td>Process</td> <td><select name=""></select></td> <td>Day?</td> <td><input type="text" size="5"></td> </tr> </table> </fieldset> <fieldset> <legend>Tasks</legend> <table border="0" width="100%"> <th width="5">select</th><th width="5">No</th><th width="150">Task</th><th width="400">Description</th><th width="100">Start Time</th> <th width="100">End Time</th><th width="100">Worked hrs</th><th width="90">Action</th> <tr> </table> <TABLE id="dataTable" width="100%" border="1"> <TD><INPUT type="checkbox" name="chk"/></TD> <td width="5"><input type="text" size="5"name=""disabled></td> <td width="150"><select name=""></select></td> <td><textarea rows="2" cols="30"></textarea></td> <td><input type="text" size="10"name=""></td> <td><input type="text" size="10"name=""enabled></td> <td><input type="text" size="10"name=""disabled></td> <td><input type="button"type="button" value="+" onclick="addRow('dataTable')"></td> <td><input type="button"type="button" value="-" onclick="deleteRow('dataTable')"></td> </tr> </table> </fieldset> <table border="0" width="100%"> <tr> <td width="122"><input type="button" value="SAVE"></td> <td></td> <td> </td> <td> </td> <td> </td> </tr> </table> </td> </tr> </table> </BODY> </HTML> I am very very new to programming and trying to create a web interface for a model. The user needs to be able to add as many compounds as they want and add a variable number of subgroups for each compound. Also, each input needs a distinct name. I have tried adapting someone else code to add/remove form inputs but am not having any luck creating subgroups. below is my code Code: <html> <head> <title>form</title> <content="text/html"; /> <script type="text/javascript"> <!-- window.onload = function () { if (self.init) init(); } var counter = 0; var counter1 = 0; function init() { document.getElementById('moreFields').onclick = moreFields; document.getElementById('moreFields1').onclick = moreFields1; moreFields(); moreFields1(); } function moreFields() { counter++; var newFields = document.getElementById('readcomp').cloneNode(true); newFields.id = ''; newFields.style.display = 'block'; var newField = newFields.childNodes; for (var i=0;i<newField.length;i++) { var theName = newField[i].name if (theName) newField[i].name = theName + counter; } var insertHere = document.getElementById('writecomp'); insertHere.parentNode.insertBefore(newFields,insertHere); } function moreFields1() { counter1++; var newFields = document.getElementById('readsubgr').cloneNode(true); newFields.id = ''; newFields.style.display = 'block'; var newField = newFields.childNodes; for (var i=0;i<newField.length;i++) { var theName = newField[i].name if (theName) newField[i].name = theName + counter1; } var insertHere = document.getElementById('writesubgr'); insertHere.parentNode.insertBefore(newFields,insertHere); } // --> </script> </head> <body> <div id="readcomp" style="display: none"> Comp name<input type=text name="comp" value="" size="2"/> Concentration<input type=text name="comp_qty" value="" size="2"/> <input type="button" value="Remove comp" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br/> <span id="writesubgr"></span> <input type="button" id="moreFields1" value="add subgroup" /><br/><br/> </div> <div id="readsubgr" style="display: none"> Subgroup Name<input type=text name="subgroup" value="" size="2"/> Quantity <input type=text name="subgroup_qty" value="" size="2"/> <input type="button" value="Remove subgroup" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /> </div> <form action="cgi_bin\show_input.pl" method="post"> <span id="writecomp"></span> <input type="button" id="moreFields" value="add comp" /><br/><br/> <input value="Run Program" type="submit"> <input value="Reset all fields" type="reset"> </form> </body></html> any help would be appreciated. thanks Am integrating a Barclays epdq shopping cart into an existing website, part of the regulations with this system is that you can only submit from one 'allowed url'. To enable access from multiple url's I need to create a 'jump page'. This needs to be a simple page that takes any variables posted to it and re-posts them (onload) onto the epdq shopping cart. The problem is I am unable to populate the form dynamically and submit onload. I have tested and it all works fine if hardcoded. Is it possible to submit a dynamically generated form using javascript? PHP Code: foreach ($_POST as $name => $value){ $newVars .= '<INPUT value="' . $value . '" name="' . $name .'" type="hidden" />'; } Code: <html> <head></head> <body onLoad="document.epdqformer.submit();"> <FORM name="epdqformer" id="epdqformer" action="https://secure2.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e" method="POST"> PHP Code: I have a form that only shows the submit (update) buttons if the value select field beside it is changed. But what is someone has JS disabled, how can I enable them? Code: <select title="3553" name="3553" onchange="JavaScript:document.cart.add3553.disabled=false;"> So i have a form with fields (30+), and about 5 of them are fields that need to pass into my dropdown (actually a dynmaic dropdown, select SOURCE, then whatever source u select it'll show options that are mysql source=$source), so it can go into my mysql query, and filter out the best results. (i.e date_of_birth, min_credits, state, etc). Needs to be done without submitting, hence javascript. Im echo'ing my query and its saying the variables i'm trying to pass are UNDEFINED. Am I not passing the vars correctly? do i need to prep the vars to "grab" them in the current field? this is what i have in my <head> Code: <script language="javascript" type="text/javascript"> function getXMLHTTP() { //fuction to return the xml http object var xmlhttp=false; try{ xmlhttp=new XMLHttpRequest(); } catch(e) { try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e1){ xmlhttp=false; } } } return xmlhttp; } function getSchool(id,hs_grad_year,dob_day,dob_month,dob_year,min_credits,state) { var strURL="findSchool.php?source="+id+"&hs_grad_year="+hs_grad_year+"&dob_day="+dob_day+"&dob_month="+dob_month+"&dob_year="+dob_year+"&min_credits="+min_credits+"&state="+state; var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('schooldiv').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } function getSub(id,cid) { var strURL="findSub.php?source="+id+"&cid="+cid; var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('subdiv').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } </script> The only var that is passing is SOURCE, and that's because its the name of the first dropdown I'm VERY new to javascript, do i need to set up like a GET method on my RECEIVING page? or can i just pass variables through? Do i need to get the "existing" data in the fields first? Thanks in advance, JT Hi, jI have a javascript script that adds/deletes input in a form. I'd like to calculate the volume for each ligne : l*h*d Then a total of all the volume fileds The data will be inserted in a php table. Thanks for your help (I hope you can understand my english) I have trouble with php but even more with javascript versions. PHP Code: -- Structure of mysql table named 'tbox' -- CREATE TABLE IF NOT EXISTS 'tbox' ( 'tboxid' int(11) NOT NULL AUTO_INCREMENT, 'tboxidtproid' int(11) NOT NULL, 'tboxdate' date NOT NULL, 'tboxL' int(11) NOT NULL, 'tboxD' int(11) NOT NULL, 'tboxH' int(11) NOT NULL, 'tboxnet' float NOT NULL, 'tboxgros' float NOT NULL, PRIMARY KEY ('tboxid') ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=55 ; The html page wiith js : PHP Code: <html> <head> <script type="text/JavaScript"> // add a box <!-- function create_champ(i){ var l = document.getElementById('l_1').value; var d = document.getElementById('d_1').value; var h = document.getElementById('h_1').value; var v = document.getElementById('v_1').value = (l * d * h) ; var i2 = i + 1; document.getElementById('champs_'+i).innerHTML = '<span id="ligne_'+i+'">L <input type="text" size="9" maxlength="9" name="l[]" id="l_'+i+'" \/> D <input type="text" size="9" maxlength="9" name="d[]" id="d_'+i+'" \/> H <input type="text" size="9" maxlength="9" name="h[]" id="h_'+i+'" \/> Volume : <input type="text" size="9" maxlength="50" name="v[]" id="v_'+i+'" value = "" " disabled="true" \/> <input type="button" value="x" id="boutton_'+i+'"onclick="delete_champ('+i+')" \/><br \/><\/span>'; document.getElementById('champs_'+i).innerHTML += '<span id="champs_'+i2+'"><input type="button" value="Add a box" onclick="create_champ('+i2+')" \/><\/span>'; } function delete_champ(i){ document.getElementById("ligne_"+i).innerHTML=""; } </script> </head> <body> <form id="1" name="addalbum" method="post" action=""> <td width="250" valign="top"><fieldset> <legend>Boxes Dimensions(mm)</legend> <table width="95%" border="0" cellspacing="0" cellpadding="3"> <tr> <span id="ligne_1"> L <input type="text" name="l[]" id="l_1" size="9" maxlength="9" value="" /> D <input type="text" name="d[]" id="d_1" size="9" maxlength="9" value="" /> H <input type="text" name="h[]" id="h_1" size="9" maxlength="9" value="" /> Volume : <input type="text" name="v[]" id="v_1" size="9" maxlength="9" value="" disabled="true" /> <input type="button" value="x" id="boutton_1" onclick="delete_champ(1)" /> <br /> </span> <span id="champs_2"> <input type="button" value="Add a box" onclick="create_champ(2)" \/></span> </table> </fieldset></td> <label> <input type="submit" name="button" id="button" value="Envoyer"> </label> </form> <?php /* insert fields in table tbox */ ?> </body> </html> Hi to all, I have a dynamic form, when a button is clicked 3 more fields appear, the function is to colect for example from date [02/02/2010] to date [10/02/2010] equals price [250$] per week and if you want another period just click the button and 3 more fields appear. How do I get all this data to PHP? Code: <script type="text/javascript"> var counter = 3; function addNew() { // Get the main Div in which all the other divs will be added var mainContainer = document.getElementById('mainContainer'); // Create a new div for holding text and button input elements var newDiv = document.createElement('div'); // Create a new text input var newText = document.createElement('input'); newText.type = "text"; newText.value = "DD/MM/AAAA"; newText.name = counter++; var newText1 = document.createElement('input'); newText1.type = "text"; newText1.value = "DD/MM/AAAA"; newText1.name = counter++; var newText2 = document.createElement('input'); newText2.type = "text"; newText2.value = "0"; newText2.name = counter++; // Create a new button input var newDelButton = document.createElement('input'); newDelButton.type = "button"; newDelButton.value = "Delete"; // Append new text input to the newDiv newDiv.appendChild(newText); newDiv.appendChild(newText1); newDiv.appendChild(newText2); // Append new button input to the newDiv newDiv.appendChild(newDelButton); // Append newDiv input to the mainContainer div mainContainer.appendChild(newDiv); counter++; // Add a handler to button for deleting the newDiv from the mainContainer newDelButton.onclick = function() { mainContainer.removeChild(newDiv); } } </script> <table style="margin-left:200px" border="0"> <tr><!-- Row 1 --> <td width="140"><b>Start Date</b></td><!-- Col 1 --> <td width="142"><b>End Date</b></td><!-- Col 2 --> <td width="140"><b>Price per week</b></td><!-- Col 3 --> </tr> </table> <div style="margin-left:200px" id="mainContainer"><div><input value="DD/MM/AAAA" name="0" type="text" ><input value="DD/MM/AAAA" name="1" type="text" ><input value="0" name="2" type="text" ><input type="button" value="New price" onClick="addNew()"></div> From the these form fields I want to be able to create an array in Javascript containing the same 'codes' that feature between the option tags (not the value="X") Code: <select name="options-1" id="options-1"> <option value="">Select an option</option> <option value="1">KA-WH</option> <option value="2">KA-BK</option> <option value="3">KA-GN</option> </select> <select name="options-2" id="options-2"> <option value="">Select an option</option> <option value="4">BADGE-1</option> <option value="5">BADGE-2</option> <option value="6">BADGE-3</option> </select> <select name="options-3" id="options-3"> <option value="">Select an option</option> <option value="7">E-WH</option> <option value="8">E-GD</option> <option value="9">E-BK</option> </select> for example, from the above, I want a JS array for 'option-1' that contains KA-WH, KA-BK and KA-GN; plus an array for 'option-2' that contains BADGE-1, BADGE-2 and BADGE-3. The above form fields will be created dynamically, may contain more or fewer items. I then want to use the JS arrays to pull in images of which filenames match the 'code' in the array. I have here a code that will automatically generate two text fields (Title & Price) when "Add another article" is pressed. I got this from the web, but I want instead of using a text field, I want it to create a drop down menu based on a mysql table, then update the price automatically (also based on the mysql table) on the other text field once a selection has been made on the drop down menu. Code: <link rel="stylesheet" type="text/css" media="screen" /> <style type="text/css"></style> <script type="text/javascript"> var elCount = 2; function add() { var parent = document.getElementById('parent'); var article = document.createElement('DIV'); article.id = 'article_' + elCount; article.name = 'article_' + elCount; // NEW LINE var article_title_label = document.createElement('LABEL'); article_title_label.appendChild(document.createTextNode('Title ' + elCount + ': ')); var article_title_text = document.createElement('INPUT'); article_title_text.id = 'article_' + elCount + '_title'; article_title_text.name = 'article_' + elCount + '_title'; // NEW LINE var article_textarea_label = document.createElement('LABEL'); article_textarea_label.appendChild(document.createTextNode('Price ' + elCount + ': ')); var article_textarea = document.createElement('INPUT'); article_textarea.id = 'article_' + elCount + '_price'; article_textarea.name = 'article_' + elCount + '_price'; // NEW LINE article.appendChild(article_title_label); article.appendChild(article_title_text); article.appendChild(article_textarea_label); article.appendChild(article_textarea); parent.appendChild(article); elCount++; } </script> <body> <div id="parent"> <div id="article_1"> <label for="article_1_title">Title 1: </label><input type="text" name="article_1_title" id="article_1_title" /> <label for="article_1_price">Price: </label><input type="text" name="article_1_price" id="article_1_price" /> </div> </div> any ideas? Thanks Hey all! So there I was newly hired and tasked with pouring through someone else's code to see what could be modified and brought up to date. After successfully finding the errors and correcting them and fulfilling the tasks my new supervisor assigned me, he slaps me on the back and says, "Well done! Now make it dynamic!" By which he meant the chapter buttons I spent hours creating from the existing code. Here's what he wants: the old code has an array, we'll call it someArray, that is assigned its values by the instructional developer as html pages are added to the course. So for example the code might look like this, Code: var someArray = new Array(4); someArray[0] = "video1/video1.html"; someArray[1] = "video2/video2.html"; someArray[2] = "video3/video3.html"; Now, each page has an associated chapter button. So video1/video1.html would have ch1Btn, video2/video2.html would have ch2Btn and so forth. Each button in turn calls a specific function which does only one thing - sets the currentPage variable to page associated with that button/array contents. For example, I have created the following functions to call each page: Code: function doCh1(){currentPage = 0; goToPage();} function doCh2(){currentPage = 1; goToPage();} function doCh3(){currentPage = 2; goToPage();} I should mention that all this is being done from within an html wrapper that calls each page into an iframe. The currentPage variable is assigned the url of one of the elements from the pageArray. My supervisor wants to be able to manually add pages to the pageArray and have the javascript code generate the associated buttons and function calls so when the learner clicks on one of the dynamically created buttons, s/he is taken to the correct page. Currently I'm using static images with the onclick calling the correct function to set my currentPage value and send the learner on his/her merry way. Is there a way to do all of this dynamically? If so, can you help me get my head around this by providing some examples? Sorry for the long post. Thank you, M Hi, I searched the web for a button that can be animated, as well as dynamic. but I couldn't find one, so I decided to try my hand at creating one. My method is similar to a post made by Bram2: http://codingforums.com/showthread.php?t=153326, however, I have found my code to be unreliable and it doesn't apply only to the area where the table is, instead of spreading across the screen. The reason for trying to create a button this way is because I'm lazy, I don't want to create a new button in a graphics editor, spending hours trying to make it uniform with the rest of the buttons on the page, every time I want a new button. Doing it this way will also enable to have buttons with mulitple lines of text. I am fairly new to javascript, so I am wondering if anyone can give me a hand making it more reliable or pointing me to a script that has already been created. I put the button Here instead of filling the post with code. Please look at it before telling me it can be done with the <button> tag, because I tried before posting here. thanks, grayatrox Edit:I have managed to get the code to do what I wanted it to do, and more efficently too. Old code is commented out in the orginal webpage. This is a working example on how to impliment the buttons. javascript: Code: /* Notes: - Each button MUST have a unique name. - You may need to create a secondary function that the button can activate like I did with the go(url) function below. - Email me (grayatrox) at 238atrox@gmail.com for bugs, or to suggest improvements. - Yes I know tables within tables is bad, if you read through my code carefully you will see where I am talking about. */ function loadButton() { //preload the buttons. image1 = new Image(); image1.src = "images/button_up_L.png"; //button up left image2 = new Image(); image2.src = "images/button_up_C.png"; //button up centre image3 = new Image(); image3.src = "images/button_up_R.png"; //button up right image4 = new Image(); image4.src = "images/button_down_L.png"; //button down left image5 = new Image(); image5.src = "images/button_down_C.png"; //button down centre image6 = new Image(); image6.src = "images/button_down_R.png"; //button down right } function createButton(buttonName, buttonText, buttonAction, id) { // create the code for a button output= "<table border='0' cellpadding='0' cellspacing='0' id="+buttonName+">"; output=output+"<tr name="+buttonName+" onclick=\""+buttonAction+"\" onmouseover=\"changeButton('down', '"+buttonName+"')\" onmouseout=\"changeButton('up', '"+buttonName+"')\">"; output=output+"<td align='right'><img id='"+buttonName+"_leftImage' src='images/button_up_L.png'/></td>"; output=output+"<td id='"+buttonName+"_middleImage' align='middle' background='images/button_up_C.png'/>"+buttonText+"</td>"; output=output+"<td align='left'><img id='"+buttonName+"_rightImage' src='images/button_up_R.png'/></td>"; output=output+"</tr>"; output=output+"</table>"; return output; } function writeButton(buttonName, buttonText, buttonAction) { // write button immediatly below where function has been called document.write(createButton(buttonName, buttonText, buttonAction)); } function writeButtonInId(buttonName, buttonText, buttonAction, id) { // write the button in an id document.getElementById(id).innerHTML=createButton(buttonName, buttonText, buttonAction); } function changeButton(action, name) { // button animation if (action== "up") { document.getElementById(name+'_leftImage').src="images/button_up_L.png"; document.getElementById(name+'_middleImage').style.backgroundImage ="url(images/button_up_C.png)"; document.getElementById(name+'_rightImage').src="images/button_up_R.png"; } else if (action== "down") { document.getElementById(name+'_leftImage').src="images/button_down_L.png"; document.getElementById(name+'_middleImage').style.backgroundImage ="url(images/button_down_C.png)"; document.getElementById(name+'_rightImage').src="images/button_down_R.png"; } } function go(url) { // written becuase there were too many ' and ". You can do this for any javascript function (I hope) document.location=url; } Hello, I'm trying to create a webpage where users can click on a dynamically generated set of questions: <?php do { ?> <p><?php echo $row_rsQuestions['question_text']; ?><?php echo $row_rsQuestions['question_type']; ?></p> <?php } while ($row_rsQuestions = mysql_fetch_assoc($rsQuestions)); ?> and by clicking on a particular question, there will be an update for their particular listing of personal questions in a MySql database. I know how to create the database update part, but I think that I would need to javascript to: 1) tell my page that it's time to update (i.e. add a particular question as soon as they click it) 2) pass along the correct variable to the database update portion of the page. Any help on these two items would be appreciated. Thank you! My application reads an array of URLs in Javascript and displays them in a table. I need to create mouseover events for each of the links (just an alert message for now.) I have tried this a few ways, but for each one the mouseover event fires for each link before anything else is loaded on the page, and when the page is loaded, no link is displayed. Here are the two ways I've tried: Code: var cell1 = document.createElement("TD"); cell1.innerHTML = '<A HREF= ' + url + 'onMouseOver="' + alert("my alert box"); + '"> my page </A>'; Code: cell1.innerHTML = '<A HREF= "' + url + '"> my page </A>'; cell1.onMouseOver = alert('alert'); I have also tried many variations of these including: Code: cell1.innerHTML = '<A HREF= "' + url + '"> my page </A>'; cell1.onMouseOver = function(){alert('alert');}; Code: var cell1 = document.createElement("TD"); cell1.innerHTML = '<A HREF= " ' + url + ' " onMouseOver=" alert("my alert box"); "> my page </A>'; But they all yield the same result, so any help would be much appreciated! I am no javascript expert, very much a beginner. I am trying to incorporate some into a web-based form. The problem is the button I created to add extra fields does not work, and I can't find exactly where the problem is. I'm in need of some help from a javascript guru. Help me enjoy my Friday afternoon by solving this! The javascript is mostly borrowed and slightly altered, the "additem" I wrote myself so that is probably where the problem lies! Here is the html: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/> <title></title> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> <link rel="stylesheet" type="text/css" href="style.css"/> <script type="text/javascript"> function showAsset(id,str) { if (str=="") { document.getElementById("assetinfo"+id).innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("assetinfo"+id).innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getasset.php?q="+str,true); xmlhttp.send(); } var noFields = "5"; function additem() { var fieldrow = document.createElement('tr'); var fieldcolumn1 = document.createElement('td'); var fieldinput = document.createElement('input'); fieldinput.name = "asset"; fieldinput.onChange = "showAsset("+noFields+",this.value)"; var fieldcolumn2 = document.createElement('td'); fieldcolumn2.id = "assetinfo"+noFields; fieldcolumn1.appendChild(fieldinput); var fieldcolumns = fieldcolumn1 + fieldcolumn2; fieldrow.appendChild(fieldcolumns); var addbefore = document.getElementById('fieldend'); document.body.insertBefore(fieldrow, addbefore); noFields = noFields++; } </script> </head> <body> <form> <table> <tr> <td><input name="asset" onChange="showAsset(1,this.value)"></td> <td id="assetinfo1"></td> </tr> <tr> <td><input name="asset" onChange="showAsset(2,this.value)"></td> <td id="assetinfo2"></td> </tr> <tr> <td><input name="asset" onChange="showAsset(3,this.value)"></td> <td id="assetinfo3"></td> </tr> <tr> <td><input name="asset" onChange="showAsset(4,this.value)"></td> <td id="assetinfo4"></td> </tr> <tr> <td><input name="asset" onChange="showAsset(5,this.value)"></td> <td id="assetinfo5"></td> </tr> <tr id="fieldend"> <td><input id="addfield" type="button" value="add item" onClick="addfield()"></td> </tr> </table> </form> </body> </html> Here is the associated getasset.php: Code: <?php $q=$_GET["q"]; $con = mysql_connect('localhost', 'root', 'root'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("assettracking", $con); $sql="SELECT * FROM assets WHERE assetID = '".$q."'"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { echo "<b>".$row['make'] ." ".$row['model'] ." - ".$row['serialnumber']."</b> | Status: ".$row['statusID']." | Comments: ".$row['comments']; } mysql_close($con); ?> The page loads and existing data is put in their correct fields. When I click 'add more' to add more fields to the form it does so and I am able to add new data. If on adding a new fields and its data I click 'add more' again it clears out the recently added data from the fields. The existing data that was present when the page first loaded is still their but all the new fields added data is cleared. how can I get it so the data stays, like in phpmyadmin when adding new fields. JS Code: function addmore(addwhat) { // count existing boxes to find out next number to use. // ? if (addwhat == 'addresses') { fieldid = 'addressesdiv'; } if (addwhat == 'namesnumbers') { fieldid = 'namesdiv'; } var dv = document.getElementById(fieldid).innerHTML; var lines = dv.match(/<br>/ig).length; if (addwhat == 'addresses') { document.getElementById('addressesdiv').innerHTML += '<textarea name="address' + lines + '" cols="30" rows="2"></textarea><br>'; } if (addwhat == 'namesnumbers') { document.getElementById('namesdiv').innerHTML += '<textarea name="name' + lines + '" cols="30" rows="2"></textarea><br>'; document.getElementById('mobilesdiv').innerHTML += '<textarea name="mobile' + lines + '" cols="30" rows="2"></textarea><br>'; } } PHP Code: <? if ($_POST['Submit'] == 'Submit') { echo("sent<br>"); for ($c = 1; $c <= (count($_POST)-1)/2; $c++) { echo("name" . $c . " = " . $_POST['name'.$c] ." mobile" . $c . " = " . $_POST['mobile'.$c] . "<br>"); } } $customer_id = "11"; // get existing data. // if not yet sent get data from databases $ok = "no"; if ($_POST['Submit'] != "Submit") { echo("<br>not sent<br>"); $res = db_query("SELECT * FROM `customer_client_names` WHERE `customer_id` = '". $customer_id ."'"); $maincount = mysql_num_rows($res); echo("<br>number of clients = ".$maincount."<br>"); for ($c = 1; $c <= $maincount; $c++) { $_POST['name'.$c] = mysql_result($res, $c-1, "client_name"); $_POST['mobile'.$c] = mysql_result($res, $c-1, "client_mobile"); echo("cn = ".$_POST['name'.$c] . " cm = ".$_POST['mobile'.$c] . "<br>"); } } else { // display last posted info echo("<br>sent<br>"); $ok = "yes"; // check if info was entrted correctly or not. for ($c = 1; $c <= ((count($_POST)-1)/2); $c++) { if ($_POST['name'.$c] != "" && $_POST['mobile'.$c] == "") { echo("<br>" . $_POST['name'.$c] ." was not given a mobile number<br>"); $ok = "no"; $maincount ++; } if ($_POST['name'.$c] == "" && $_POST['mobile'.$c] != "") { echo("<br>" . $_POST['mobile'.$c] ." mobile was not given a name<br>"); $ok = "no"; $maincount ++; } } } if ($ok == "no") { ?> <form name="form1" method="post" action="?ac=<?=$menu_item;?><? echo("&phpsession=" . $phpsession); ?>"> <div style="width: 850px;"> <div id="namesdiv" style="float: left; padding-right: 10px;">Client's Names<br> <? for ($c = 1; $c <= ((count($_POST)-1)/2)+1; $c++) { if ($_POST['name'.$c] != "" || $_POST['mobile'.$c] != "") { ?> <textarea name="<?='name'.$c;?>" cols="30" rows="2"><?=$_POST['name'.$c];?></textarea><br> <? } } ?> </div> <div id="mobilesdiv" style="float: left;">Client's Mobile numbers<br> <? for ($c = 1; $c <= ((count($_POST)-1)/2)+1; $c++) { if ($_POST['name'.$c] != "" || $_POST['mobile'.$c] != "") { ?> <textarea name="<?='mobile'.$c;?>" cols="30" rows="2"><?=$_POST['mobile'.$c];?></textarea><br> <? } } ?> </div> </div> <br style="clear: both;"> <a href="#" onClick="javascript:addmore('namesnumbers'); return false;" >Add more</a> <input type="hidden" name="customer_id" value="<?=$customer_id;?>"> <input type="submit" name="Submit" value="Submit"> </form> <? } ?> I type something on the current textarea/input and all the values get removed after I add another field. Is there a solution? Code: <script language="Javascript" type="text/javascript"> <!-- //Add more fields dynamically. function addField(area,field,limit) { if(!document.getElementById) return; //Prevent older browsers from getting any further. var field_area = document.getElementById(area); var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area. //Find the count of the last element of the list. It will be in the format '<field><number>'. If the // field given in the argument is 'friend_' the last id will be 'friend_4'. var last_item = all_inputs.length - 1; var last = all_inputs[last_item].id; var count = Number(last.split("_")[1]) + 1; //If the maximum number of elements have been reached, exit the function. // If the given limit is lower than 0, infinite number of fields can be created. if(count > limit && limit > 0) return; //Older Method field_area.innerHTML += "<li><textarea id='steps' name='steps[]' rows='5' cols='40'></textarea><br /><input id='steps_image' name='steps_image[]' /></li>"; } //--> </script> <ol id="steps_area"><li> <textarea id='steps' name='steps[]' rows='5' cols='40'></textarea><br /><input id='steps_image' name='steps_image[]' /> </li> </ol> <input type="button" value="Add" onclick="addField('steps_area','',15);"/> Hi All, i know how to create a dynamic form or DIv ..but what i do not know is how to create a dynamic form/ or div into a previous dynamic one.. i need basically to see 5 dynamic forms / DIV in cascade where each one trigger the one coming after.. For what i need that : i have my user inserting information on the level 1. let say Copagny info 2- then he will be asked if he wants to add a sub level information ( subform) for that compagny or even many subforms at the same level .. and so on... 3- those sub level ( subforms ) can also call their respective subforms.. Any idea how to design this ? thanks |