JavaScript - Adding Form Elements To An Array
Similar TutorialsYears ago I created HTML that employs checkboxes and textboxes. I am now writing JS with the intention of adding flexibility and limiting redundancy. I am not sure I truly understand how to correctly interact the two though. For example, one of my scripts have arrays that contain the names of the checkboxes and textboxes, with a 'for' loop to document.write() them to references within the HTML code. This does not seem to be working for me though. Here is what I have thus far (in short): Code: <script language="javascript"> var teamNames = new Array(3); teamNames[0]="South Africa"; teamNames[1]="Mexico"; teamNames[2]="Uruguay"; for (i=0; i<=31; i++) { document.write("<p>" + teamNames[i] + "<\/p>"); } </script> </head> <body> <tr><td>Jun 11</td><td><input type="checkbox" name="teamNames[0]" value="teamAbbr[0]"></td> </body> I've left out a lot of the code (to include the teamAbbr array, but you get the points. I've tried moving the JS within the HTML body and playing with the reference syntax, but nothing so far. Any help would be great! I am trying to develop a function that creates a certain number of form elements based on a certain number that a user inputs. It does not do what I want it to do (obviously). The problem lies within the TextBoxAppear() function. The function worked when I tested it by adding just text (document.getElementByID('leftcolumn').innerHTML = "<p>test function</p>" so I know for a fact whatever I added to the function is the problem. What has been added to the function and needs fixing is in BOLD Code: <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Exercise 4</title> <style type = "text/css"> #leftcolumn { width: 300px; border: 1px solid red; float: left} #rightcolumn { width: 300px; border: 1px solid red; float: left} </style> <script> function start() { var button = document.getElementById( "submitButton" ); button.addEventListener( "click", TextBoxAppear, false ); } function TextBoxAppear() { var numberOfValuesInput = document.getElementByID( 'NumberOfValuesField' ); var numberOfValues = parseFloat( numberOfValuesInput.value ); var textBoxCreation = "<form action ="http://www.deitel.com"><p>"; for ( var i = 1; i < numberOfValues; ++i ) { textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>"; } textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form> document.getElementById('leftcolumnn').innerHTML = textBoxCreation; } window.addEventListener( "load", start, false ); </script> </head> <body> <form action ="http://www.deitel.com"> <p><label>Number of values to be calculated: <input id = "numberOfValuesField" type = "text"></label> <input id = "submitButton" type = "button" value = "Submit"></p> </form> <div id ="leftcolumn"><p>test left column</p></div> <div id ="rightcolumn"><p>test right column</p></div> </body> </html> Hi Folks - I have a form that has an array of input values: <input type="text" name=txtValue[] /> <input type="text" name=txtValue[] /> I do this so I can loop through the values in php... now...that's the easy part... the hard part comes to this: next to each of those boxes is a search button that allows the user to open up a popup window that they can search for an item, and select the item. Once they select the item it should populate that particular input box with the selected item. I can easily do this with a uniquely named input box, but can't seem to figure out how to do it with an array of input boxes... any idea? Hi, I'm pulling my hair out to create a simple function! I am creating an array based on form elements. I then am trying to create an IF (and nested IF) statement to check if the fields are empty and then with the nested IF statement use certain fields to create mathematical functions. So far I have this: function QuantityMWh(form) { var formchk = document.forms[0] for (i = 0; i < formchk.elements.length; i++) { if (formchk.elements[1].value == "" && formchk.elements[2].value == "") { alert("Please fill out all fields.") break } } } It's only checking the first field and not the second, and vice versa. i.e. if only one field has text then it passes. What am I doing wrong? Thanks. Guys, For some reason my script only works when I have at lease two checkboxes. To simulate the problem just run it once with two html input checkbox elements -> check one checkbox and press submit -> it works -> Now remove one input checkbox field and check the remaining checkbox & submit -> Bamm doesn't work... What am I doing wrong ? Code: <html> <head> <script> function Check(chk) { for (i=0; i < chk.length; i++) chk[i].checked=document.ListActionForm.Check_ctr.checked ; } function desubmit() { if(get_args()==false) {alert("nothing_selected");return false;} if(labelling(true)) return false; } function labelling(s) {return true;} function get_args() { s=chkboxa2str(document.ListActionForm['listaction[]']); if(s)alert(s); if(s.length<8)return false; else return s; } function chkboxa2str(chkbox_a) { var list = ""; for(var i = 0; i < chkbox_a.length; i++){ if(chkbox_a[i].checked) { list += chkbox_a[i].value + " "; } } return list; } </script> </head> <body> <form action="?h=1296078874" method="post" name="ListActionForm" onsubmit="return desubmit()"> <input type='checkbox' name='listaction[]' value='2010102909103530'> Testbox 1<br> <input type='checkbox' name='listaction[]' value='2010102909103532'> Testbox 2<br> <input type="Submit" name="Submit" value="Versturen" > </form> </body> </html> I am very new to javascript. I have a problem getting to any element from this form generated by the jsp page using struts. Please show me how to get to item[0].totalAmount for example, so that I can create a function to calculate the calculateTotal(). So far, when I do the alert, it is only valid up to document.myForm.item; the document.myForm.item[0] is invalid according to the alert. Any help is very much appreciated. function calculateTotal(){ alert(document.myForm.item); } <form name="myForm" method="post" action="/myAction.do"> <table id="display" border="1"> <tr> <th scope="col" id="totalAmount">Total Amount</th> <th scope="col" id="adjustmentAmount>Adjustment Amount</th> <th scope="col" id="newAmount">NewAmount</th> </tr> <tr> <td><input type="text" name="item[0].totalAmount" id="totalAmount" value="100" readonly="readonly"></td> <td><input type="text" name="item[0].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[0].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> <tr> <td><input type="text" name="item[1].totalAmount" id="totalAmount" value="350" readonly="readonly"></td> <td><input type="text" name="item[1].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[1].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> </table> </form> im creating a completely javascript only game. Your doge, and your trying to stay away from falling rocks. I have doge, and i can move him. I have only 1 falling rock on the canvas at once. I need to add more rocks falling at once, but i don't know how to go about doing it. here is my code: document.onkeydown = checkKey; //listener for left or right arrow key function checkKey(e) { e = e || window.event; if (e.keyCode == '37') { left(); }else if (e.keyCode == '39') { right(); } } function draw(image, x, y){ //for drawing to canvas var canvas = document.getElementById("game"); var context = canvas.getContext("2d"); var imageObj = new Image(); imageObj.onload = function() { context.drawImage(imageObj, x, y); }; imageObj.src = image; } x = 0; //doge starting location y = 340; draw("doge.png",x,y); function left(){ draw("clear.png", x, y); draw("doge.png", x-50, y); x = x-50 } function right(){ draw("clear.png", x-20, y); draw("doge.png", x+50, y); x = x+50 } x1 = Math.floor((Math.random() * 600) + 1); y1 = -20; //chooses random location of rock function main(){ draw("clearrock.png",x1,y1); draw("doge.png",x,y); draw("rock.png",x1,y1+20); y1 = y1+20 if(y1 === 500){ y1 = -20; x1 = (Math.floor((Math.random() * 60) + 1))*10; //chooses new random location of rock } if(x1 > x-30 && x1 < x+140){ if(y1 === y-20){ alert("Dead doge"); clearInterval(mainint); } } } var mainint = setInterval(function(){main()}, 100); //game ticks Hello I've been struggling trying to get a small order form to work the way I want it to. Here is a link to the live page: http://www.watphotos.com/introductio...otography.html And here is the code in question: Code: <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ var initial = 0 var total = 0; var services = 0; function addServices() { initial = 150 total = initial services = 0; $("input:checked").each(function(){ value = $(this).attr("value"); services += parseInt(value); }); } $(function() { addServices(); total += services; $("form").before('<p class="price"></p>') $("p.price").text("Total Price: US$" + total); }); $("input:radio, input:checkbox").click(function () { addServices(); total += services $("p.price").text("Total Price: US$" + total); }); }); </script> I have two questions... Question 1 How can I make this piece of script act a little smarter. Look at the order form, I'm catering for up to 4 people and providing lunch for them. If they select 3 people and the spaghetti bol for lunch, it's only adding $10 where it should be adding $30. Obviously this is simple multiplication but since the values in my form are prices it makes it a little tricky. I'm guessing an onselect on the first part of the form which changes the pricing of the other items would be the way to go, but how do I do this? Question 2 The "Total Price" is placed before the <form> tag by the script. This is ok but it's not where I want it. How can I position this text elsewhere in the document? Thanks in advance! I tried the following code based on a post I saw somewhere else about summing all the elements of an array together. When I tried it though I couldn't seem to get it working. Can someone please point out what I did wrong or tell me a different way to sum array elements together? Thanks. Code: <script type="text/javascript"> Array.prototype.sum = function() { for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]); return sum; } var myArray=[1,2,3,4,5]; document.write(myArray.prototype.sum); </script> Hi again!! This is my code to add and delete dynamic rows and auto calculate the amount field by multiplying qty and rate. PHP Code: <form name="staff_reg" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>" method="post" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <table border="0" cellpadding="1" cellspacing="0" class="normal-text" align="left"> <tr align="center"> <td width="10" class="forhead" style="white-space:nowrap;"> </td> <td width="92" class="forhead" style="white-space:nowrap;">Qty</td> <td width="94" class="forhead" style="white-space:nowrap;">Rate</td> <td width="94" class="forhead" style="white-space:nowrap;">Amount</td> </tr> </table> <tr align="left"> <td class="forhead" style="white-space:nowrap;"><input type="button" value="Add Row" onClick="addRow('dataTable')" > <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" ></td> <table border="0" id="dataTable" cellpadding="1" cellspacing="0" class="normal-text"> <tr> <td width="10" class="forhead" style="white-space:nowrap;"><input type="checkbox" name="chk[]"/></td> <td width="92" class="forhead" style="white-space:nowrap;"> <input type="text" name="qty[]" style="width:80px;" onblur=""> </td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" name="rate[]" style="width:80px;" value=""></td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" onblur="getValues('qty[]','rate[]','amt[]')" name="amt[]" style="width:80px;"></td> </tr> </table> <table border="0"> <tr> <td>Total:</td> <td><input type="text" name="total[]" style="width:80px;" value=""></td> </tr> <tr> <td colspan="2"> <input name="Submit" type="submit" value="Save" style="text-decoration:none" /> <input type="reset" value="Cancel" onclick="window.location.href='<?php echo $_SERVER['PHP_SELF'];?>'"> </td> </tr> </form> <script type="text/javascript"> function getValues(objName,objName2,objName3) { var var3 = ""; var arr = new Array(); arr = document.getElementsByName(objName); arr2 = document.getElementsByName(objName2); arr3 = document.getElementsByName(objName3); for(var i = 0; i < arr.length; i++) { for(var i = 0; i < arr2.length; i++) { for(var i = 0; i < arr3.length; i++) { var obj1 = document.getElementsByName(objName2).item(i); var var2 = obj1.value; var obj = document.getElementsByName(objName).item(i); var var1 = obj.value; var obj3 = document.getElementsByName(objName3).item(i); var var3 = obj3.value; var var4 = var1 * var2; document.getElementsByName(objName3).item(i).value=var4; } } } } 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 = 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> I would like to know that how can I show the value of all the elements in array "amount" in total field?? I'm using the jquery plugin found here. I love the look but I have a form that uses functions like this: Code: function cascadeCountry(value) { if (document.getElementById("srchlookstate_province") != null) { http.open('get', 'cascade_search.php?a=country&v=' + value ); document.getElementById('srchlookstate_province').innerHTML=" "+loadingTag; http.onreadystatechange = handleResponse; http.send(null); } } So, when you select a country and it retrieves the state/province text input, the jquery css is not applied to it. Is there something I need to add to the code above or to the jquery initialization code he Code: $(function() { $("form.jqtransform").jqTransform(); }); Hey guys. I need a little help with checking elements in my array. I created an array of size 50 and initialized all elements to 1. What i want to do is if the user types in the number "1" into the prompt box, i want it to check the first 15 elements and increase only one of the elements by 1, and if the element has already been increased by 1 then i want it to check the next element and see if its been increased, if the element has been increased then it needs to move on to the next one and check that. If the element is 1, then it can be increased by "1", if the element is 2 then i need it to check the next element. If all elements within the first 15 have increased by 1, it should just alert the user that all slots have been assigned. Is there a way to do this? Thanks for your time
Hey All, I have completed most of a homework assignment that I am working on. I am able to .push desired elements into an array: Code: //Insert variable into the Array function insertElem(){ //Insert and sort first array, but not second array if(nameInput.value != ""){ studName2.push(nameInput2.value); } else{ alert("Value to be inserted cannot be Null"); } //Refresh display area clearAndShow2(); } What I would like to do is be able to store and display the created array "permanently" until I decide to remove the elements. My current method to hold the elements, until the page is refreshed, is: Code: //Refresh second array function clearAndShow2(){ nameInput2.value = ""; messageBox2.innerHTML = ""; messageBox2.innerHTML += "Groups: " + "<br />" + studName2.join("<br />") + "<br />"; } I appreciate the assistance. Hi All, Simple newbie question here - I want to initialize an array with "myString.length" elements, and I want every element to be prepopulated with "*" instead of blank. Is there any way of doing this? Code: var myString = '123456'; var trialVar = new Array[myString.length] document.write('TEST ' + '<BR><BR>' + trialVar); (I want every element of trialVar to be "*", I cant just manually add them as myString.length will vary) Any help would be mega appreciated - thank you Hi Guys I am new to javascript programming and I am trying to get elements from one array to another, here is an example of what I am trying to do; Code: oneArray[0] = anotherArray[10]; Essentially, moving the data in index 10 of anotherArray to the index 0 of oneArray. I have tried using a variable as a place holder such as; Code: placeHolder = anotherArray[10]; oneArray[0] = placeHolder; I know i'm doing something idiotic somewhere along the line, I just can't figure out what I need to do. Hi, I am stumped. I have been trying unsuccesfully for three days to figure something out, and it has brought me here. I am a noob javascripter, so please bear with me. I have created a page with an input button that refers to a function: Code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)"> <meta name="created" content="Thu, 26 May 2011 03:39:57 GMT"> <meta name="description" content=""> <meta name="keywords" content=""> <title>Meltmedia Web Intern Test</title> <style type="text/css"> <!-- body { color:#000000; background-color:#FFFFFF; } a { color:#0000FF; } a:visited { color:#800080; } a:hover { color:#008000; } a:active { color:#FF0000; } --> </style> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <LINK REL=StyleSheet HREF="what.css" TYPE="text/css" MEDIA=screen> <script type="text/javascript"> //function ChangeBackground() <!--{ // document.getElementById("column2").style.backgroundColor="#ffbdaa"; // document.getElementById("row1").style.backgroundColor="#ffbdaa"; // document.getElementById("row3").style.backgroundColor="#ffbdaa"; // document.getElementById("row4").style.backgroundColor="#ffbdaa"; // document.getElementById("mainbody").style.backgroundColor="#f7d7cd"; // } --> function ChangeBackground() { var colors = document.getElementsByClassName("changeme"); //alert(colors.length); for (var i = 0; i < colors.length; i++) { if (colors[i].className="changeme") { colors[i].style.backgroundColor="ffbdaa"; } } } //if (document.getElementsByClassName('changeme')[5].style.backgroundColor="#e8e8e00") { // document.getElementsByClassName('changeme')[5].style.backgroundColor="#ffbdaa"; // } //div1 original color is #e8e8e8 //div2 original color is #e2ebe4 //tablerows original color is #ccddd0 </script> </head> <body> <div id="mainbody" class="changeme"> <img id="header" src="osx_header.jpg"> <div id="inset"> <div id="column1" class="column1"> <p class="text0">Lorem Ipsum Dolor Sit Amet</p> <p class="text1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sed est et mi varius euismod sed nec neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultricies pulvinar lacinia. <a href="http://www.google.com/" rel="nofollow" target="_blank" style="color:blue">This is a link.</a> </p> <p class="text1" style="font-size:16px;">Lorem Ipsum Dolor Sit Amet</p> <p class="text1">Sed a felis et eros gravida dignissim. Quisque lobortis magna non purus vulputate pellentesque. Mauris sit amet felis felis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam molestie lacinia arcu vitae pretium.<sup>2.3</sup> </p> <div id="unordered_list"> <ul id="blue_bullets"> <li>Vestibulum ante erat, laoreet quis pellentesque quis, tincidunt fermentum turpis. <li>Maecenas in mollis massa. <ul> <li>Ut tempus tincidunt molestie. Phasellus eget nulla id erat scelerisque porttitor vel pharetra nibh. <li>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </ul> <li>Aenean ligula massa, tempor sed pulvinar sit amet, imperdiet a nisi. </ul> </div><!--end of ordered list--> <div id="button"> <!-- <img src="btn-click-here.gif"> --> <input type="button" onClick="ChangeBackground()" value=" "> </div><!--end of button--> <table id="table1"> <tr id="firstrow"> <th id="row1" class="changeme"></th> <th id="row2" class="changeme"><strong>header1</strong></th> <th id="row3" class="changeme"><strong>header2</strong></th> <th id="row4" class="changeme"><strong>header3</strong></th> </tr> <tr> <td>one</td> <td>1234</td> <td>bears</td> <td>abcd</td> </tr> <tr> <td>two</td> <td>5678</td> <td>beets</td> <td>efgh</td> </tr> <tr> <td>three</td> <td>9101</td> <td>battlestar</td> <td>ijkl</td> </tr> <tr> <td>four</td> <td>1121</td> <td>galactica</td> <td>mnop</td> </tr> </table> <!--end of table--> <ol class="ordered"> <li>Integer molestie sodales risus eu commodo. <i>Duis eget est dapibus neque congue</i> accumsan id eu nibh. </li> <li>Proin malesuada hendrerit lobortis. Integer et erat leo. Praesent nec justo nulla. <i>Sed in dolor id neque faucibus consequat.</i> </li> <li>Vestibulum sit amet justo id <strong>risus tempus ornare.</strong> Etiam faucibus urna volutpat lorem dictum imperdiet. </li> </ol> </div> <!--end of column1--> <div id="column2" class="changeme"> <p class="text00"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</strong></p> <p class="text2">Aenean sed est et mi varius euismod sed nec neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultricies pulvinar lacinia. Sed a felis et eros gravida dignissim. Quisque lobortis magna non purus vulputate pellentesque.</p> <p class="text2">Mauris sit amet felis felis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam molestie lacinia arcu vitae pretium. Vestibulum ante erat, laoreet quis pellentesque quis, tincidunt fermentum turpis. Maecenas in mollis massa. Ut tempus tincidunt molestie.</p> <p class="text2">Phasellus eget nulla id erat scelerisque porttitor vel pharetra nibh. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean ligula massa, tempor sed pulvinar sit amet, imperdiet a nisi. Nulla ullamcorper posuere dolor, ac rutrum velit sollicitudin ac. Ut felis leo, ultricies a bibendum ac, luctus semper massa.</p> </div> <!--end of column2--> </div> <!--end of inset--> </div> </body> </html> i would like to change certain style elements of the array each time the button is clicked. I have 5 color sets i would like use for the page, so i would like the button to trigger the color change in a loop, ie when the last color group is reached, the next click returns to the original color set and it continues again. This is a demo page, not for actually publication. I am trying to teach myself javascript and this is an idea that came to me. The things i want to change are the background color of two div's and the top row of a table. My style sheet is seperate, and I will also do the same for the javascript once I can get it to work properly. Thank you in advance for any help. I wrote js functions to reset a php form (multiple questions). The below works: Code: function resetForm(){ resetGroup(document.forms[0].answer1); resetGroup(document.forms[0].answer2); } Answer1 and answer2 are the elements of $_POST array. (<input name="answer1"> in php). In this example, I tried with only two questions, but I have up to 35 questions in one form. Instead of writing the above resetGroup() 35 times, I want to for-loop it. I tried Code: function resetForm(){ for (var i=1; i<3; i++){ resetGroup(document.forms[0]."answer"+i); } That didn't work. Could someone help me to make the loop work? Or would someone have better or simpler idea? Thanks. I'm writing a simple Chess Record keeping app (still ), and i'm having a problem with the Screen.X and Screen.Y variables to compare with the coordinate variables stored in an Array. The project is a little large, so here's the live version (on my website). Though it will only work if you run it from your local disk. http://daomingjin.googlepages.com/ScoreMate.html the zip archive of this is he http://daomingjin.googlepages.com/ScoreMatev1.zip the main JavaScript function file is he http://daomingjin.googlepages.com/Core.js the particular function in question is this: Code: var PieceThere = isPieceHere(ClosestX, ClosestY); function isPieceHere(x, y) { // Test to see if there is an Element at point x,y for (var i = 0; i < 32; i++) { if (PieceLocationXcoord[i] == x) { if(PieceLocationYcoord[i] == y) { // There is a piece there var Result = "True"; } } } return Result; } i have placed alert() boxes in many places in the code above, and i can tell the following: the function is being activated the coordinates of x and y are able to be accessed inside the function the arrays called PieceLocationYcoord and PieceLocationXcoord both have the values in them that are returned by the ClosestX and ClosestY function however, every time , the function continues to return "Undefined". I have even tried manually setting var Result = "True" inside the last if-then block, and still returns undefined. i have also tried using the alert box inside this function (before the variable return Result; is called) and still get undefined as the message from the alert box. |