JavaScript - Looping Through Form Elements?
Hi there
I have a form with elements named (& id) 1 through 5 Why can't I loop through all my form elements like this... Code: function toggle(){ for (var i=1;i<=5;i++) { var y = document.getElementById(i); y.style.backgroundColor = '#FFFFFF'; } } The error I get is y is null??? If I hard code the id's like this... var y = document.getElementById('2'); it works fine?? Please Help NEWB Similar TutorialsHi guys, I am new around here so ... greetings! I've lately stepped up a little problem with one of my personal projects that i am working. I'm writing an aspx webpage, which includes web user controls inside it. The webuser controls are within a web form (id=form1 runat=server) which resides in the main.aspx page. 1. First of all, is there a way to find a SPECIFIC control inside the webuser control (ascx) using Javascript in the main.aspx? 2. If not (which i think it is), which is the best way to do it? The snippet i tried was this: '---------------------------------------------------- function FindControl(elem_type,elem_id) { var elem = document.form1.elements; for(var i = 0; i < elem.length; i++) { if ((elem[i].type==elem_type) && (elem[i].id.indexOf(elem_id)!=-1)) { alert(elem[i].id); } } } '---------------------------------------------------- The problem is that the alerted id of the control isn't the exact id that i've written in the webuser control, but a string that seems to concatenate all the parent html controls of the control that i am searching for, ex. if the control that i'm searching for is <asp:Textbox id="txtName" runat="server"/> and it is nested inside a groupbox <groupbox:Group id="grp_1" runat="server"/> then the alerted id isn't TXTNAME but GRP_1_TXTNAME etc. Two questions then: 1. Is the search in the "for statement" hierarchicly ordered? I mean, if i have another <asp:textbox id="txtName2" runat="server"/> inside the groupbox, will the first only be rendered if i put a break after the "if statement"? 2. Is there a way to get the exact id name of the controls without the "indexOf"? Thanks in advance! 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'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(); }); Here is the code in question: Code: for (var x = 2; x < 6; x++) { var form = document.playerAction["action" + proNum]; form[x] = null; form[x] = z[x-2]; if (Player[x-1].health == 0) { form.splice(x-2,1) } } The code retrieves document.playerAction["action1"] (A select input type) and removes options 2-end (there is a max of 6). Then, if a certain player (x-1 causes it to loop 1-4) has a health of 0, it splices out that element). Everything works fine, except I get an error saying that "Object #<an HTMLSelectElement> has no method 'splice' " and it refuses to execute the if. How do I work around this? 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. 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 all. I have a form named "theForm". How can I loop through this form elements that have an "id" ATTRIBUTE to them and then populate my ids array? var ids = new Array; for(i=0; i<document.theForm.elements.length; i++) { IF ELEMENT HAS AN ID ATTRIBUTE POPULATE ids array } Hi all I have a form with one or more DIV elements inside it. When I try to count form elements I get result=0? How is this possible? See the example: Code: <html> <head> <script language="javascript"> function Count() { alert(document.frm1.elements.length); for(i=0; i<document.frm1.elements.length; i++) { alert(document.frm1.elements[i].name); } } </script> </head> <body> <form id="frm1" name="frm1"> <div id="div1" name="div1">.</div> </form> <input type="button" onclick="Count();" /> </body> </html> If I put other element (textbox) inside the form, the count result is correct. Is DIV not an element?! How can I count one or more DIV and inner DIV's? Thanks for your help. Z. 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> Hello, I'm in need of some help. I have a form that I want to clone and add up to 5 duplicates with slight changes. The changes a Add a second question and another set of related radio buttons for only the duplicates. Change the title in the Header to increment by 1 ex. Header 1, Header 2... I also would like to make the form elements "id" and "names" unique. Also, continue to use the add and remove button at the bottom. I hope this is doable. Any help will be appreciated. I have included my existing code. NOTE: for a visual, I mocked up the the original form and 1 copy of the fields in the html, not to be used. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> <script type="text/javascript" src="http://tablesorter.com/jquery-latest.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function() { $('#btnAdd').click(function() { var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have var newNum = new Number(num + 1); // the numeric ID of the new input field being added var newElem = $('#section' + num).clone().attr('id', 'section' + newNum); newElem.children(':first').attr('id', 'first' + newNum).attr('name', 'first' + newNum).val(''); newElem.children(':first').attr('id', 'last' + newNum).attr('name', 'last' + newNum).val(''); newElem.children(':first').attr('id', 'phone' + newNum).attr('name', 'phone' + newNum).val(''); newElem.children(':first').attr('id', 'email' + newNum).attr('name', 'email' + newNum).val(''); newElem.children(':first').attr('id', 'yes' + newNum).attr('name', 'yes' + newNum).val(''); newElem.children(':first').attr('id', 'no' + newNum).attr('name', 'no' + newNum).val(''); $('#section' + num).after(newElem); $('#btnDel').attr('disabled',''); if (newNum == 5) $('#btnAdd').attr('disabled','disabled'); }); $('#btnDel').click(function() { var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have $('#section' + num).remove(); // remove the last element $('#btnAdd').attr('disabled',''); // enable the "add" button // if only one element remains, disable the "remove" button if (num-1 == 1) $('#btnDel').attr('disabled','disabled'); }); $('#btnDel').attr('disabled','disabled'); }); </script> <form id="myForm"> <div id="section1" style="margin-bottom:4px; border-bottom:1px solid #000; width: 400px;" class="clonedInput"> <br> <br> <div style=" font-weight:bold; border: 1px solid #000; padding:4px;background:#CCC; font-size:18px; margin-bottom:5px;">Header</div> First: <input type="text" name="first1" id="first1" /> <br> <br> Last: <input type="text" name="last1" id="last1" /> <br> <br> <br /> <div style=" font-weight:bold;padding:4px;">Header 2</div> <div>Show this question and radios on load of page.</div> <div> <input type="radio" id="yes1" class="eRad" name="yes1" value="" /> <label class="" for="yes">Yes</label> <input type="radio" id="no1" class="eRad" name="no1" value="" /> <label class="" for="no">No</label> </div> Phone: <input type="text" name="phone1" id="phone1" /> <br> <br> Email: <input type="text" name="email1" id="email1" /> </div> <div id="section1" style="margin-bottom:4px; border-bottom:1px solid #000; width: 400px;" class="clonedInput"> <br> <br> <div style=" font-weight:bold; border: 1px solid #000; padding:4px;background:#CCC; font-size:18px; margin-bottom:5px;">Header 2 (increment this number)</div> <div>Show this new question and radios on all copies</div> <div> <input type="radio" id="yes_a2" class="eRad" name="yes_a2" value="" /> <label class="" for="yes">Yes</label> <input type="radio" id="no_a2" class="eRad" name="no_a2" value="" /> <label class="" for="no">No</label> </div> First: <input type="text" name="first2" id="first2" /> <br> <br> Last: <input type="text" name="last2" id="last2" /> <br> <br> <br /> <div style=" font-weight:bold;padding:4px;">Sub Header 2 (increment this number)</div> <div>Show this question and radios on load of page.</div> <div> <input type="radio" id="yes_a2" class="eRad" name="yes_a2" value="" /> <label class="" for="yes">Yes</label> <input type="radio" id="no_a2" class="eRad" name="no_a2" value="" /> <label class="" for="no">No</label> </div> Phone: <input type="text" name="phone2" id="phone2" /> <br> <br> Email: <input type="text" name="email2" id="email2" /> </div> <div style="margin-top:10px;"> <input type="button" id="btnAdd" value="add another name" /> <input type="button" id="btnDel" value="remove name" /> </div> </form> </body> </html> -Cheers Hi all, I had posted earlier on the NaN issue. I have worked some more on my test file. Basically I want the user to select an option depending on whether he/she has Paracetamol in syrup or drops form. Once this is selected, automatically a different div for syrup or for drops should be seen depending on what the user selected earlier. After this on pushing the calculate button, the output should be appropriate depending on the strength of the solution either for drops or syrup. I have put together what I think code that should work but it stubbornly refuses to do otherwise. I have attached the relevant file. If it doesn't work, obviously there is something wrong but what it is eludes me. Any help will be appreciated greatly, 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> I wanted to know if document.getElementById works while accessing form elements. I tried doing this just for testing purposes This code doesnt work function validateForm() { var val = document.getElementById("id_login").getAttribute("value"); alert(val); return false; } but this does function validateForm() { alert(document.myForm.text_login.value ); return false; } Why doesnt document.getElementByid work with form objects.it works with all non form HTML objects.. I am trying to set up a looping structure that tests to see if the user enters a value. If the textbox is null then a global variable is false otherwise a checkbox is checked and the global variable is true. below is what i have done so far, please assist me. var isValid = false; window.onload = startForm; function startForm() { document.forms[0].firstName.focus(); document.forms[0].onsubmit = checkEntries; alert("You have been added to the list") } function checkEntries() { var menus = new Array(); var formObject = document.getElementsByTagName('*'); for (var i=0; i < formObject.length; i++){ if (formObject[i] == "myform") menus.push(formObject[i]); if (document.forms[0].firstName.value.length==0 || document.forms[0].firstName.value.length == null){ isValid= false; alert("Please enter a first name"); } else (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].lastName=="" || document.forms[0].lastName== null){ alert("Please enter a last name"); isValid = false; } else (document.forms[0].check1.checked=true); isValid=true; if (document.forms[0].email=="" || document.forms[0].email== null) { alert("Please enter a valid email"); } else return (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].bDate=="" || document.forms[0].bDate== null) { isValid=false; alert("please make sure you enter a valid birth date."); } else (document.forms[0].check0.checked=true); isValid=true; } } here is the form html... <form name="myform" > <input type="checkbox" name="check0" class="check0" id="check0" > First: <input type="text" name="firstName" id="firstName"> <BR> <input type="checkbox" name="check1" class="check1" id="check1" > Last: <input type="text" name="lastName" id="lastName" ><BR> <input type="checkbox" name="check2" class="check2" id="check2" > E-Mail: <input type="text" name="email" id="email"> <BR> <input type="checkbox" name="check3" class="check3" id="check3" > Birthday (mm/dd/yyyy): <input type="text" name="bDate" id="bDate"> <BR> <input type="submit" value="Join our mailing List" /> </form> hi there, I need to ask my users to input some numbers via textbox(or prompt) using a DELIMITER (,) between each digit. Then The program will display(list) when clicking a button. for this I will use three columns in the first column I have (2,4,6,9) to prompt. in the second column I have (3,4,7,10) to prompt. in the third columns I have (5,6,11,14) to prompt so the first lines should look like: 2,3,5 2,3,6 2,3,11 .... .... .... and the last line : 9,10,14 there should be 4x4x4=64 rows/lines How can we achieve this ? Thanks in advance I need to loop through an array like this one: [1,2,4,8,8,16,32,64] I don't really know how to do this, so a little guidance would be great. Basically, I have 4 vars: a b c and d in the form of (ax + b)(cx + d) inside the loop something like this: i++ a = array[i] If (a*b > Math.floor(a) && a*b < Math.ceil(a)){ then increment i again and do the loop again} else{ break the loop and set leave a = array[i] } A code sample or something would be really nice (I don't know how to do the parts that are written out in text... Thanks! } |