JavaScript - Creating Fields Dynamically Upon Clicking And Data From Mysql Tables
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 Similar TutorialsI 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);"/> 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> <? } ?> Hi guys, I created a form that contains about 10 form fields and would like to add the option to dynamically add more sets of those 10 fields if a user clicks a word or a button but I need help. I'm a beginner when it comes to JavaScript and would appreciate any help. This is what I need to generate dynamically. Can someone give me an idea of how to get started please? Code: <div id="dynamicInput"> <ul> <li>1</li> <li><input name='textfield1' type='text' size='10' /></li> <li><select name='commodity' width='100' style='width: 100px'> <option>Option 1</option> </select></li> <li><input name='textfield2' type='text' size='5' /></li> <li><input name='textfield3' type='text' size='10' /></li> <li><input name='textfield4' type='text' size='10' /></li> <li><input name='textfield5' type='text' size='10' /></li> <li><input name='textfield6' type='text' size='5' /></li> <li><input name='textfield7' type='text' size='5' /></li> <li><input name='textfield8' type='text' size='5' /></li> </ul> </div> Hello, I want to add rows and columns on click. So, i have a table with columns and rows and I had a add and remove button. So I want the user to be able to add/remove more rows if they have multiple inputs/outputs. So what I want is when the user clicks on add.png, I want another row of Input and Description to appear underneath the current one. Here is my code.. Code: <img src="images/add.png" width="15" height="15" align="right" > <div class="open"> <table width="200" border="0"> <tr> <td class="propertyCol">Input: </th> <td class="propertyCol"><input class="text ui-widget-content ui-corner-all" value="" style="width:210px"></input></th> <td class="propertyCol">Description: </th> <td class="propertyCol"><textarea name="" cols="45" rows="1" class="text ui-widget-content ui-corner-all"></textarea> </th> <td class="propertyCol"><a href="javascript:removeElement();" ><img src="images/remove.png" alt="" width="15" height="15" /></a> </th> </tr> </table> <table width="200" border="0"> <tr> <td class="propertyCol">Output: </th> <td class="propertyCol"><input class="text ui-widget-content ui-corner-all" style="width:200px"></input></th> <td class="propertyCol">Description: </th> <td class="propertyCol"><textarea name="" cols="45" rows="1" class="text ui-widget-content ui-corner-all"></textarea> </th> <td class="propertyCol"><a href="javascript:removeElement();" ><img src="images/remove.png" alt="" width="15" height="15" /></a> </th> </tr> </table> </div 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 I have a form with 3 fields that will allow a user to search a database of clients by either name, email, or client id number. However, I would like the user to only be able to put information in one field. It can be done be either deleting the other two fields when the user inputs information into a different field, or by disabling the other two fields when the user enters information in one (and also frees up all fields if the user ends up deleting what they entered). I've searched and found several helps that were close to what I need but not exactly. I was wondering if anyone would be able to help. Below is a start of what I had. Basically, it will disable the fields when I mouse out of them but won't re-enable them when I mouse back in. As you can see, I tried various combinations of events. (My code below also doesnt null out the other fields when the user opts to use a different field than the one they first began to enter info in). Any help is much appreciated and if this needs more explanation I will try to clarify better. Thanks Code: <html> <head> <script type="text/javascript"> function makeDisable($ID){ var x=document.getElementById($ID) x.disabled=true } function makeEnable(){ var x=document.getElementById($ID) x.disabled=false } </script> </head> <body> <form name='selectclient' action='client_edit.php' method='get'> <table> <tr> <td align='right'>Client ID:</td> <td><input id='id' type='text' size='20' name='client_id' onmouseout="makeDisable('id')" onmouseover="makeEnable('id')" value='' /></td> </tr> <tr> <td align='right'>Client Email:</td> <td><input id='email' type='text' size='20' name='client_email' onblur="makeDisable('email')" onfocus="makeEnable('email')" value='' /></td> </tr> <tr> <td align='right'>Client Name:</td> <td> <select id='name' name='client_name' onblur="makeDisable('name')" onmouseover="makeEnable('id')"> <option value=''>-- Select --</option> <option value='1' >Ted</option> <option value='2' >David</option> <option value='3' >Zack</option> </select> </td> </tr> <tr> <td align='left'><input value='Edit' type='submit' name='submit' /></td> </tr> </table> </form> </body> </html> I'd like to create a basic form where 3 text input fields are named with the following names referrerId, referrerId2 & referrerId3. My goal is once the text fields within the form are populated with the users data, then once the user clicks submit, a new browser window opens up (in parent window preferably), navigating to the following url exactly as shown. Highlighted in red is the dynamic information I'd like appended. Vacation Packages &referrerId=FIRSTNAME&referrerId2=LASTNAME&referrerId3=AGENTNUMBER Any help would be greatly appreciated. Thanks! Evening all. Here's a snippet: Code: canvases[i] = document.createElement('canvas'); canvases[i].style.width = '3px'; canvases[i].style.height = '100%'; canvases[i].getContext("2D"); canvases[i].fillRect(1,0,1,table_height); I'm trying to dynamically create a canvas element. Later in the script it gets attached to the DOM, and this works fine if the last two lines are missing. I end up with a canvas element that is 3px wide and 100% of the containing div tall. However, the last two lines make it crash, with the error report 'canvases[i].fillRect is not a function'. If I change the last two lines to Code: var drawing = canvases[i].getContext("2D"); drawing.fillRect(1,0,1,table_height); it says 'drawing is null'. Something seems to be going wrong with the getContext bit, because setting the height and width work fine. Any ideas? It behaves the same if I append the canvas element to the DOM before trying to do the drawing as well. This is in FF4.0.1 with a xhtml1-strict.dtd doctype and valid html. Thanks, Chris im trying to create a script for greasemonkey (tried getting help from their discussion forums, but no one ever answers), but its still written in javascript. so here is what im trying to do. Ive got a dynamically created division that aligns to the right of the browser window. Now im trying to put links inside it as you normally would with like a document.write statement or other methods. The only problem is, any method i try wont work for me. heres my code, maybe someone could give me some things i could try. Code: function QuickLinks() { var body = document.body; var div2 = document.createElement("div"); div2.setAttribute('class','QL'); div2.setAttribute('style','background-color: #692510;width: 200px;height: 500px;top: 2cm;position: absolute;right: 5px;z-index: 4;'); var links = document.createTextNode("where i want my links"); //now with that statement it just writes text, ive tried document.write and many other methods and nothing seems to work. div2.appendChild(links); //this just inserts the links into the div. body.appendChild(document.createElement('br')); body.appendChild(div2); } QuickLinks(); ok so I am trying to create a function that creates an array comprised of filenames based on a given range. I.E if 2-8 is selected and a foldername of UMCP/ and a common name of college is also given, the function should return and array such as [UMCP/college2.jpg,UMCP/college3.jpg.....UMCP/college8.jpg]. Here is what I've got but the alert that should tell me the filename of the first image says it is undefined, how can i fix this? Code: function getArrayPhotosNames (total,count,first,last) { /*window.alert("get Array Photo Names");*/ var folderName = document.getElementById("photofold").value; var Alias = document.getElementById("commonName").value; for (var i=0; i>=total; i+=1) { var imageNum = i+first; var filename = folderName + Alias + imageNum + ".jpg"; window.alert("image will be stored as"+filename); photosArrayGlobal[i]= filename; } window.alert("the first photo is" +photosArrayGlobal[0]); var countnum = count.value; if (count === 0) { window.alert("randomize time") var randomArray = photosArrayGlobal.sort( randomize() ); var randomPhoto= document.getElementById("myImage"); randomPhoto.setAttribute("src", randomArray[photoIndexGlobal]); } else { var firstPhoto=document.getElementById("myImage"); firstPhoto.setAttribute("src", photosArrayGlobal[photoIndexGlobal]) } } Forgive me, I come from a ColdFusion background and DOM manipulation is not one of my strongest assets. I am trying to dynamically create (and also delete) a row inside a table, which contains three cells that each have three form elements (a input box, a select drop-down box that is populated by a query to a database, and a textarea). Now all the JavaScript/jQuery examples I've seen for dynamically creating elements are very basic, nothing this complex. Could I get some help?! This is what I'm trying to dynamically create so that the user can add more options but also delete them. Would the jQuery clone() function be a good choice for this? Code: <tr> <td> <input type="text" id="rejectName" /> </td> <td> <select id="divSelectReason"> <option value="" selected="true">Enter Rejection Reason</option> <cfoutput query="queryReasonReturn"> <option>#codeAndReason#</option> </cfoutput> </select> </td> <td> <textarea id="editReason" cols="30"></textarea> </td> </tr> Now when a row is dynamically created I also have to access those values as well, so I would assume using a variable that counts each row created, and appends that iteration to the name of that particular element. Hi, I would just like to know how I would dynamically add another table once text fields in the existing table is clicked on. So pretty much what I have is a table with 5 textboxes lined up horizontally in the first row along with couple of buttons in the second row. What I want is that once one text box is clicked, another table like the one above is created and appears below that initial table. So this is the inital table that should be replicated on each click: Code: <table> <tr> <td><input type="text" /></td> <td><input type="text" /></td> <td><input type="text" /></td> <td><input type="text" /></td> <td><input type="text" ></td> </tr> <tr> <td><button /></td> <td><button /></td> </tr> </table> How would I go about achieving this? Thanks Hello! Im having problem generating the labels for content created by the following function: Code: function setOutput(){ if(httpObject.readyState == 4){ var answer = httpObject.resultsponseText.split(","); var results = document.getElementById("resultsultadosScan1"); var article = document.createElement("div"); var weight = document.createElement("div"); var price = document.createElement("div"); article.className = "article"; weight.className = "weight"; price.className = "price"; document.getElementById('outputText0').value = httpObject.innerHTML= answer[0]; document.getElementById('outputText1').value = httpObject.innerHTML= answer[1]; document.getElementById('outputText2').value = httpObject.innerHTML= answer[2]; article.innerHTML = httpObject.innerHTML= answer[0]; weight.innerHTML = httpObject.innerHTML= answer[1]; price.innerHTML = httpObject.innerHTML= answer[2]; results.appendChild(article); results.appendChild(weight); results.appendChild(price); } } A friend wrote this sample script to achieve generation of labels on my script, but I have been trying for hours with no luck, can someone take a look and tell me the correct usage of this script: Code: function createLabel() { var target = document.getElementById("target"); var label = document.createElement("label"); var text = document.createTextNode("Article"); label.appendChild(text); target.appendChild(label); } Can you help me with the correct "combination" using my script above, a "real life" example? Thanks a lot! 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. I almost have the website finished, at least functionally (the complicated backend). It will arguably be one of the coolest history sites on the web. But I am running into some technical problems, and want to ask you about them, as I am at a point where that is my only alternative. First is in the website: http://184.73.182.71/timelines/search2.fwx There is the line: Timeline.loadXML("http://184.73.182.71/14OZH01XY.xml", function(xml, url) { eventSource.loadXML(xml, url); }); This is loading an XML data file into the time-line, and it works fine. The question is, why cant I dynamically load this data from a process, like: Timeline.loadXML("http://184.73.182.71/getdata.php?page=10", function(xml, url) { eventSource.loadXML(xml, url); }); It is returning the exact same thing, yet it dosent work. Somebody suggested the following: eventSource.loadXML(eventSource.loadXMLText(xmlstring,),"http://184.73.182.71/getdata.php?page=10"); But that dosent seem to work either. And can I do the same thing with a script tag, such as: <script src="http://184.73.182.71/getdata.php?page=10" type="text/javascript"></script> Is this illegal? Thanks in advance for looking at this. I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* I have 2 types of addresses 1. Permanent address > Postal code, Street, City, State, Country 2. Current address > Postal code, Street, City, State, Country and a check box 'Copy from Permanent address' with Current address when i checked that check box then all values from 'Permanent address' will be copy to 'Current address' Please send me the code 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); ?> Ok so Im going to break down what Im trying to do and hopefully someone can point me to a possible solution without getting all technical. I have 2 div tags. the first is a content container more or less. the second is a container for a php built calender (using html tables). Basically when the page loads the php builds the calenders html table code. each td element has an onclick event handler. The goal is to have the javascript handler execute when any non empty cell is clicked (non empty being that it has a date associated with it and is not a blank space filler). This is the easy part. The hard part is that each calendar day potentially has certain information associated with it stored in a mysql database. Im wanting input fields within the first container div to autopopulate with the information from the database (if any) for whatever day is clicked. Ive search around and heard things like javascript cant do mysql queries directly, and heard mention of ajax. So im stumped as to how to accomplish this. whether i need an external php script for the queries (perhaps inside a php function that can return data to the javascript that calls it?), but if that is plausable would it cause page loads or the like to the user? i really dont want to have to learn ajax for this one page, just seems excessive, but i do need a way to make the content in the first div populate with the respective database data for the selected day on the calendar. any thoughts, comments, or solutions that dont involve yet another web language would be greatly appreciated. thanks
|