Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Aug 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    javascript multiple fields / ajax

    Hi there,

    I am adding Multiple Fields to a form using JavaScript - and I am using AJAX to return data.

    My problem is that when I add a new field - it gets a unique id no (num) in the code below.

    I am also neededing to assign this (num) to the Ajax ElementId

    Please help me!

    Regards,
    Jonathan

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Add/Remove child: Javascript</title>
    <script language="javascript" type="text/javascript">
    <!--
    function addEvent() {
    var ni = document.getElementById('myDiv');
    var numi = document.getElementById('theValue');
    var num = (document.getElementById("theValue").value -1)+ 2;
    numi.value = num;
    var divIdName = "my"+num+"Div";
    var newdiv = document.createElement('div');
    newdiv.setAttribute("id",divIdName);
    //newdiv.innerHTML = "Element Number " + num + " has been added! <a href=\"javascript:;\" onclick=\"removeElement(\'"+divIdName+"\')\">Remove</a>";
    newdiv.innerHTML = "<input name='ProductCode"+num+"' type='text' class='FormFieldCode' id='ProductCode"+num+"' onChange='ajaxFunction();' value='code' /><input name='ProductName"+num+"'' type='text' class='FormFieldName' id='ProductName"+num+"' value='product name' /><input name='ProductPrice"+num+"' type='text' class='FormFieldCode' id='ProductPrice"+num+"' value='R 0.00' /><a href=\"javascript:;\" onclick=\"removeElement(\'"+divIdName+"\')\">&nbsp;Remove</a>";
    ni.appendChild(newdiv);
    }

    //Browser Support Code
    function ajaxFunction(){
    var ajaxRequest; // The variable that makes Ajax possible!
    var pCode; // The Product Code variable

    try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
    } catch (e){
    // Internet Explorer Browsers
    try{
    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e){
    // Something went wrong
    alert("Your browser broke!");
    return false;
    }
    }
    }

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){

    if(ajaxRequest.readyState == 4){
    document.getElementById("ProductName"+num).value == ajaxRequest.responseText;
    }
    }
    pCode = document.getElementById("ProductCode"+num).value;
    ajaxRequest.open("GET", 'getproduct.php'+'?'+'code'+'='+pCode, true);
    ajaxRequest.send(null);
    }

    function removeElement(divNum) {
    var d = document.getElementById('myDiv');
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
    }
    </script>
    <style type="text/css" media="screen">
    .updated {
    background: #FFE2AF;
    color: #000;
    border: 2px solid #ccc;
    padding: 1em;
    }
    </style>
    </head>

    <body>
    <form name="AjaxForm" action="add-remove-javascript.html" method="post">
    <input type="hidden" value="0" id="theValue" />
    <p><a href="javascript:;" onclick="addEvent();">Add Products to Order</a></p>
    <div id="myDiv"> </div>
    <div id="submitDiv"><input name="submit" type="button" value="Submit" /></div>
    </form>
    </body>
    </html>

  • #2
    New Coder
    Join Date
    Oct 2007
    Location
    Washington
    Posts
    86
    Thanks
    3
    Thanked 2 Times in 2 Posts
    Here, this will get you started as It works great for me!!

    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    // tabledeleterow.js version 1.2 2006-02-21
    // mredkj.com
    
    // CONFIG notes. Below are some comments that point to where this script can be customized.
    // Note: Make sure to include a <tbody></tbody> in your table's HTML
    
    var a = 'a'; // this is being set via script
    var RADIO_NAME = 'totallyrad'; // this is being set via script
    var TABLE_NAME = 'tblSample'; // this should be named in the HTML
    var ROW_BASE = 1; // first number (for display)
    var hasLoaded = false;
    
    window.onload=fillInRows;
    
    function fillInRows()
    {
    	hasLoaded = true;
    	addRowToTable();
    	addRowToTable();
    }
    
    // CONFIG:
    // myRowObject is an object for storing information about the table rows
    function myRowObject(one, two, three, four)
    {
    	this.one = one; // text object
    	this.two = two; // input text object
    	this.three = three; // input checkbox object
    	this.four = four; // input radio object
    }
    
    /*
     * insertRowToTable
     * Insert and reorder
     */
    function insertRowToTable()
    {
    	if (hasLoaded) {
    		var tbl = document.getElementById(TABLE_NAME);
    		var rowToInsertAt = tbl.tBodies[0].rows.length;
    		for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
    			if (tbl.tBodies[0].rows[i].myRow && tbl.tBodies[0].rows[i].myRow.four.getAttribute('type') == 'radio' && tbl.tBodies[0].rows[i].myRow.four.checked) {
    				rowToInsertAt = i;
    				break;
    			}
    		}
    		addRowToTable(rowToInsertAt);
    		reorderRows(tbl, rowToInsertAt);
    	}
    }
    
    function Calc(){
    var frm = document.form0;
    var tbl = document.getElementById(TABLE_NAME);
    var total=0;
    
    for (var xyz=0;xyz<tbl.tBodies[0].rows.length;xyz++){
    cellval=tbl.tBodies[0].rows[xyz].cells[2].childNodes[0].value;
    if (cellval.length>0&&!isNaN(parseInt(cellval))) total+=parseInt(cellval);
    }
    frm.SUM.value=total;
    }
    
    /*
     * addRowToTable
     * Inserts at row 'num', or appends to the end if no arguments are passed in. Don't pass in empty strings.
     */
    function addRowToTable(num)
    {
    	if (hasLoaded) {
    		var tbl = document.getElementById(TABLE_NAME);
    		var nextRow = tbl.tBodies[0].rows.length;
    		var iteration = nextRow + ROW_BASE;
    		if (num == null) { 
    			num = nextRow;
    		} else {
    			iteration = num + ROW_BASE;
    		}
    		
    		// add the row
    		var row = tbl.tBodies[0].insertRow(num);
    		
    		// CONFIG: requires classes named classy0 and classy1
    		row.className = 'classy' + (iteration % 2);
    	
    		// CONFIG: This whole section can be configured
    		
    		// cell 0 - text
    		var cell0 = row.insertCell(0);
    		var textNode = document.createTextNode(iteration);
    		cell0.appendChild(textNode);
    		
    		// cell 1 - input text
    		var cell1 = row.insertCell(1);
    		var txtInp1 = document.createElement('input');
    		txtInp1.setAttribute('type', 'text');
    		txtInp1.setAttribute('name', 'a' + iteration + '_1');
    		txtInp1.setAttribute('size', '40');
    		txtInp1.setAttribute('value', iteration); // iteration included for debug purposes
    		cell1.appendChild(txtInp1);
    
        var cell1a = row.insertCell(2);
        var txtInp2 = document.createElement('input');
        txtInp2.type = 'text';
        txtInp2.value = '';
        txtInp2.setAttribute('name', 'a' + iteration + '_2');
        txtInp2.size = 4;
        txtInp2.setAttribute("onChange", "Calc()");
        txtInp2.setAttribute("onBlur", "Calc()");
        txtInp2.setAttribute("onFocus", "Calc()");
        txtInp2.setAttribute("onClick", "Calc()");
        txtInp2.setAttribute("onKeydown", "Calc()");
        txtInp2.setAttribute("onKeyup", "Calc()");
        cell1a.appendChild(txtInp2);
    		
    		// cell 2 - input button
    		var cell2 = row.insertCell(3);
    		var btnEl = document.createElement('input');
    		btnEl.setAttribute('type', 'button');
    		btnEl.setAttribute('value', 'Delete');
    		btnEl.onclick = function () {deleteCurrentRow(this)};
    		cell2.appendChild(btnEl);
    		
    		// cell 3 - input checkbox
    		var cell3 = row.insertCell(4);
    		var cbEl = document.createElement('input');
    		cbEl.setAttribute('type', 'checkbox');
    		cell3.appendChild(cbEl);
    		
    		// cell 4 - input radio
    		var cell4 = row.insertCell(5);
    		var raEl;
    		try {
    			raEl = document.createElement('<input type="radio" name="' + RADIO_NAME + '" value="' + iteration + '">');
    			var failIfNotIE = raEl.name.length;
    		} catch(ex) {
    			raEl = document.createElement('input');
    			raEl.setAttribute('type', 'radio');
    			raEl.setAttribute('name', RADIO_NAME);
    			raEl.setAttribute('value', iteration);
    		}
    		cell4.appendChild(raEl);
    		
    		// Pass in the elements you want to reference later
    		// Store the myRow object in each row
    		row.myRow = new myRowObject(textNode, txtInp1, txtInp2, cbEl, raEl);
    	}
    }
    
    // CONFIG: this entire function is affected by myRowObject settings
    // If there isn't a checkbox in your row, then this function can't be used.
    function deleteChecked()
    {
    	if (hasLoaded) {
    		var checkedObjArray = new Array();
    		var cCount = 0;
    	
    		var tbl = document.getElementById(TABLE_NAME);
    		for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
    			if (tbl.tBodies[0].rows[i].myRow && tbl.tBodies[0].rows[i].myRow.three.getAttribute('type') == 'checkbox' && tbl.tBodies[0].rows[i].myRow.three.checked) {
    				checkedObjArray[cCount] = tbl.tBodies[0].rows[i];
    				cCount++;
    			}
    		}
    		if (checkedObjArray.length > 0) {
    			var rIndex = checkedObjArray[0].sectionRowIndex;
    			deleteRows(checkedObjArray);
    			reorderRows(tbl, rIndex);
    		}
    	}
    }
    
    // If there isn't an element with an onclick event in your row, then this function can't be used.
    function deleteCurrentRow(obj)
    {
    	if (hasLoaded) {
    		var delRow = obj.parentNode.parentNode;
    		var tbl = delRow.parentNode.parentNode;
    		var rIndex = delRow.sectionRowIndex;
    		var rowArray = new Array(delRow);
    		deleteRows(rowArray);
    		reorderRows(tbl, rIndex);
    	}
    }
    
    function editCurrentRow(obj)
    {
    	if (hasLoaded) {
    		var editRow = obj.parentNode.parentNode;
    		var tbl = editRow.parentNode.parentNode;
    		var rIndex = editRow.sectionRowIndex;
    		var rowArray = new Array(editRow);
    		callPrompt(rowArray);
    	}
    }
    
    function reorderRows(tbl, startingIndex)
    {
    	if (hasLoaded) {
    		if (tbl.tBodies[0].rows[startingIndex]) {
    			var count = startingIndex + ROW_BASE;
    			for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
    			
    				// CONFIG: next line is affected by myRowObject settings
    				tbl.tBodies[0].rows[i].myRow.one.data = count; // text
    				
    				// CONFIG: next line is affected by myRowObject settings
    				tbl.tBodies[0].rows[i].myRow.two.name = a + count; // input text
    
    				// CONFIG: next line is affected by myRowObject settings
    				// tbl.tBodies[0].rows[i].myRow.two.name = a[1]_2 + count; // input text
    				
    				// CONFIG: next line is affected by myRowObject settings
    				var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' '); // for debug purposes
    				tbl.tBodies[0].rows[i].myRow.two.value = count + ' was' + tempVal[0]; // for debug purposes
    				
    				// CONFIG: next line is affected by myRowObject settings
    				tbl.tBodies[0].rows[i].myRow.four.value = count; // input radio
    				
    				// CONFIG: requires class named classy0 and classy1
    				tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
    				
    				count++;
    			}
    		}
    	}
    }
    
    function deleteRows(rowObjArray)
    {
    	if (hasLoaded) {
    		for (var i=0; i<rowObjArray.length; i++) {
    			var rIndex = rowObjArray[i].sectionRowIndex;
    			rowObjArray[i].parentNode.deleteRow(rIndex);
    		}
    	}
    }
    
    function openInNewWindow(frm)
    {
    	// open a blank window
    	var aWindow = window.open('', 'TableAddRow2NewWindow',
    	'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
    	
    	// set the target to the blank window
    	frm.target = 'TableAddRow2NewWindow';
    	
    	// submit
    	frm.submit();
    }
    
    </script>
    </head>
    <body>
    
    <form action="" method="get" name="form0">
    <p>
    <input type="button" value="Add" onclick="addRowToTable();" />
    <input type="button" value="Insert [I]" onclick="insertRowToTable();" />
    <input type="button" value="Delete [D]" onclick="deleteChecked();" />
    <input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
    </p>
    <table border="0" cellspacing="0" id="tblSample">
      <thead>
      <tr>
        <th colspan="5">Sample table</th>
      </tr>
      <tr>
        <th>#</th><th>Input Text</th><th>Add</th><th>Delete</th><th>D</th><th>I</th>
      </tr>
      </thead>
      <tbody></tbody>
    </table>
    <input type="text" name="SUM" value="0" onfocus="if(this.value=='0')this.value='';" onblur="if(this.value=='')this.value='0';" readonly size="4">
    </form>
    
    
    
    
    <a href="javascript:if (typeof(window.document.body.outerHTML) != 'undefined'){'<xmp>'+window.document.body.outerHTML+'</xmp>'} else if (typeof(document.getElementsByTagName('html')[0].innerHTML) != 'undefined'){ '<xmp>'+document.getElementsByTagName('html')[0].innerHTML+'</xmp>'} else if (typeof(window.document.documentElement.outerHTML) != 'undefined'){ '<xmp>'+window.document.documentElement.outerHTML+'</xmp>'} else { alert('Your browser does not support this.') }">View Source!</a>
    </body>
    </html>
    "The one closer to the truth is the one still learning"


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •