JavaScript - Way To Take Values Added To Div And Place In Form Field
I'm trying to add the ui autocomplete function to some form fields using a facebook style, but I'm not sure how to get more than one value to actually pass to the form field. As my script is now it only takes the last selected value into the hidden form field. Here's my current script:
Code: <div id="editcbprofileinterests"> <div id="formWrap"> <div id="interests" class="ui-helper-clearfix"> <input id="cb_intereststerm" type="text"> <input id="cb_interests" name="cb_interests" type="hidden"> </div> </div></div> <script type="text/javascript" src="autocomplete/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="autocomplete/js/jquery-ui-1.8.custom.min.js"></script> <script type="text/javascript"> $(function(){ //attach autocomplete $("#cb_intereststerm").autocomplete({ //define callback to format results source: function(req, add){ //pass request to server $.getJSON("autocomplete/autocominterests.php?callback=?", req, function(data) { //create array for response objects var suggestions = []; //process response $.each(data, function(i, val){ suggestions.push(val.cb_intereststerm); }); //pass array to callback add(suggestions); }); }, //define select handler select: function(event, ui) { //create formatted interest var interest = ui.item.value, span = $("<span>").text(interest), a = $("<a>").addClass("remove").attr({ href: "javascript:", title: "Remove " + interest }).text("x").appendTo(span); //add interest to interests div span.insertBefore("#cb_intereststerm"); //add interest to hidden form field $('input[name=cb_interests]').val(interest); }, //define select handler change: function() { //prevent 'to' field being updated and correct position $("#cb_intereststerm").val("").css("top", 2); } }); //add click handler to activities div $("#interests").click(function(){ //focus 'to' field $("#cb_intereststerm").focus(); }); //add live handler for clicks on remove links $(".remove", document.getElementById("interest")).live("click", function(){ //remove current activity $(this).parent().remove(); //correct 'to' field position if($("#interests span").length === 0) { $("#cb_intereststerm").css("top", 0); } }); }); </script> Similar TutorialsHello all. I have created a snippet of javascript code that will do the following: 1. read the window URL 2. depending on the window URL, a word will be placed into a hidden form field. 3. Person submits form...etc., etc. Here is what I have. Let's say that I have a single landing page with a simple form on it. I would like to reference the referred URL by pulling a part of the window URL into a hidden field of the form. Let's say the three URLs a http://www.whatever.com/index.htm?id=ref1 http://www.whatever.com/index.htm?id=ref2 http://www.whatever.com/index.htm?id=ref3 I have created a javascript that takes the exact URL and check for equality. If the URL is equal, it will place the corresponding id into the hidden form field. See my code below. Code: <script type="text/javascript"> var lead_source = window.location.href { if (lead_source == "http://www.whatever.com/index.htm?id=ref1") { document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref1'>"); } else if (lead_source == "http://www.whatever.com/index.htm?id=ref2") { document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref2'>"); } else if (lead_source == "http://www.whatever.com/index.htm?id=ref3") { document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref3'>"); } } </script> What I am looking to do is modify the code to only look at the "id" variable, not the entire URL. That way, if I add any additional items to the URL I will not have to change the code. I guess I am looking for an extra step of parsing the URL...maybe. Thanks for your help Can someone help me I am trying to get these two values, firstname and lastname to both go into the same output box on a form. I want them to show up alongside one another like so nameform.output2.value=firstname + " " + lastname; but the values are assigned within seperate if statements as you can see below.. so I dont know how to get them to merge.. I am kinda new with javascript so any help will be very useful. Thakns very much. Code: function checkform(nameform){ var firstname=new Array(); firstname[0]="johndefinition"; firstname[1]="jamesdefinition"; var lastname=new Array(); lastname[0]="smithdefinition"; lastname[1]="simpsondefinition"; if (document.getElementById("namebox").value.indexOf("John")!=-1) {nameform.output2.value= firstname[0];} if (document.getElementById("namebox").value.indexOf("James")!=-1) {nameform.output2.value= firstname[1];} if (document.getElementById("namebox").value.indexOf("Smith")!=-1) {nameform.output2.value=lastname[0];} if (document.getElementById("namebox").value.indexOf("Simpson")!=-1) {nameform.output2.value=lastname[1];} } 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 Hi, i know i should have 2 fields for a first and last name in my form but i dont - and was wondering if someone would be able to help me with - or has - a java script valadation rule to only allow a one letter character (letter in between spaces such as a middle initial) in a text field if at least 2 words are also included (2 words of at least 2 or more characters) so if the user input ' John H ' an error prompt would display until one more word is added/at least 2 words are found right now im using the below coding to allow at least 2 words in the text field but would like to see if its possible to enhance it so it will only block a one letter word if there are less than 2 other words in the form - right now if any words is added with less than 2 characters it will display an error... if anyone knows of a better form of code that needs a minimum of 2 words added and still allows single characters such as middle initials to in a validation script i'd greatly appreciate your help... i get lost on validation process' 'cheers' in advance to anyone that may know of something or a site that can point me in a better direction function(value,element){return this.optional(element)||/^((\b[a-zA-Z]{2,80}\b)\s*){2,}/ Hi, I am setting up an email form & i would like the subject field to hold multiple values, the forrm will be something like this: Name:Mr A Date: 01/01/01 Reason:Football I want the form to send an email without opening an email client & I would like the subject field to look like this: Subject: Mr A, 01/01/01, Football or Subject Mr A - 01/01/01 - Football Can anyone tell me if this is possible, if if is can you please point me in the right direction. Thanks Hello everyone, I have done a lot of research looking for answers on this one but unable to find anything that helps. I have a couple of questions on a page and each are contained in there own form. The questions themselves use checkboxes. I would like the page to not refresh and jump to the top of the page after they submit there answer. So on questions that use radio buttons I have been using Code: <input type="submit" value="Submit" onclick="get_radio_value(); return false;" /> for the submit buttion and that works perfect. I try and use it on questions that use checkboxes and it doesnt work so as a work around I am using the form's action attribute to set it to a link on the page. Here is my form code: Code: <form name="question2" action="#q2">2. <strong>Multiple choice:</strong><a name="q2"></a> Which patient or patients could be transferred to another hospital under the EMTALA Act?<br /> <input type="checkbox" value="a" name="aquestion" />Smith, Bill<br /><input type="checkbox" value="b" name="bquestion" />Wells, Patricia<br /> <input type="checkbox" value="c" name="cquestion" />Hamilton, Larry<br /> <input type="checkbox" value="d" name="dquestion" />Rodriquez, Brad<br /><input type="checkbox" value="e" name="equestion" />Baker, Madison<br /><input type="checkbox" value="f" name="fquestion" />Kahn, Brent<br /> <input type="checkbox" value="g" name="gquestion" />Cahill, Mark<br /><input type="submit" onclick="get_radio2_value()" value="Submit" /></form> <script type="text/javascript" src="first_triage_java_clinical.js"> </script> and here is the javascript code if it helps: Code: function get_radio2_value() { var w = 400; var h = 400; var wleft = (screen.width/2)-(w/2); var wtop = (screen.height/2)-(h/2); var wrong = "<html><head><style type='text/css'> * {margin: 0; padding:0; border:0;}</style>\ <title>Incorrect, try again!</title></head><body><bgsound src='Plbt.wav'>\ <a href='javascript:window.close()'><img src='wrong.jpg'></a></body></html>"; var right = "<html><head><style type='text/css'> * {margin: 0; padding:0; border:0;}</style>\ <title>You are Correct!</title></head><body>\ <a href='javascript:window.close()'><img src='right.jpg'></a></body></html>"; var correct = "false"; if (document.question2.cquestion.checked) { if(document.question2.dquestion.checked) { if(document.question2.equestion.checked) { if(document.question2.fquestion.checked) { if(document.question2.gquestion.checked) { var correct = "true"; } } } } } if (document.question2.aquestion.checked) { var correct = "false"; } if (document.question2.bquestion.checked) { var correct = "false"; } if (correct != "true") { var popup = window.open('','','resizeable=no,scrollbars=no,width=221,height=112, top='+ wtop +', left='+ wleft); popup.document.write(wrong); pops.document.close(); } else { var popup = window.open('','','resizeable=no,scrollbars=no,width=221,height=112, top='+ wtop +', left='+ wleft); popup.document.write(right); pops.document.close(); } } Hi all, I'm a beginner in JavaScript can someone please help me to resolve this issue and thanks in advance for your help! What I'm trying to do is.. When you select multiple <div> get the value of each one and save in separate hidden fields accordingly. What needs to happen is... Click div 1 --> if hidden field1 value is "none", save there, else check hidden field 2 if that's "none" save in hidden field 2 Click div 2 --> if hidden field1 value is "none", save there, else check hidden field 2 if that's "none" save in hidden field 2 Here's what I've come up with so far (currently I'm using JQuery) The problem with this is that no matter what div I click in which order it only updates the 1st hidden field Code: <div id="click1" name="click1" value="123" onclick="abc()"/>Click 1</div> <div id="click2" name="click2" value="225" onclick="def()"/>Click 2</div> <input id="passenger_1" name="passenger_1" type="hidden" value="none" /> <input id="passenger_2" name="passenger_2" type="hidden" value="none" /> <script> function abc() { var pasvalue = $('#click1').attr('value'); var pas1_value = $('#passenger_1').attr('value'); var pas2_value = $('#passenger_2').attr('value'); if(pas1_value == "none"){ $('#passenger_1').attr('value', pasvalue); }else if (pas2_value == "none"){ $('#passenger_2').attr('value', pasvalue); }} function def() { var pasvalue = $('#click2').attr('value'); var pas1_value = $('#passenger_1').attr('value'); var pas2_value = $('#passenger_2').attr('value'); if(pas1_value == "none"){ $('#passenger_1').attr('value', pasvalue); }else if (pas2_value == "none"){ $('#passenger_2').attr('value', pasvalue); }} </script> I have to update the rowid(assigned to checkbox) whenever the textbox value is updated and this needs updating value of document.getElementsByName('rf_select[]') when checkbox value matches the textbox id. There can be mutliple number of rows each with a uniqueID (checkbox value) that matches with the textboxID onload. Code :- <td align="center"><input type='checkbox' name='rf_select[]' id='rf_select' value="rowId" CHECKED border="none"/> <td align="left"><input type='text' name='policy_no' id="rowId" size='25' value="test" onBlur=handleRowId('policy_no'); /></td> <script language="javascript"> function handleRowId(){ var arr = new Array(); var rowarr = new Array(); arr = document.getElementsByName('policy_no'); rowarr = document.getElementsByName('rf_select[]'); for(var i = 0; i < arr.length; i++) { var obj = arr.item(i); //alert(obj.id + " = " + obj.value); for(var j=0; j< rowarr.length; j++){ if(rowarr[j].value == obj.id){ document.getElementsByName('rf_select')[j].value = rowarr[j].value+"#@#"+obj.value; } } } } </script> I am having problem assigning values here - document.getElementsByName('rf_select')[j].value = rowarr[j].value+"#@#"+obj.value; Any help is appreciated. like for example i have text areas named upload1 and upload2 when I click or add input on upload1 a drop down list below upload2 will not change, but when I add input on upload2 the dropdown will select "parts" I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> I have a order form page and on submitting it opens a new web page that displays the order totals. Below is my code and most probably wrong but for me it seems logic. Please assist. Order Form: Code: <td colspan="1" height="120" align="left"> <select style="margin-left: 60px; background-color: #00FF77;" name="prod_bed_359" onchange="calculateValue(this.form)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> R359</td></tr> New page I called a unction to print: Code: function itemsOrdered() { var beds = document.forms[2].prod_bed_359.value; document.write("<pre><strong>Description\t\tQuantity\tPrice</strong></pre>"); document.write("<pre>Doggie Bed\t\t" + beds + "</pre>"); } This is still basic as I need to get this right before adding the prices and totals which is also extracted from the order page. How can I add a form field value to a url. I tried the below but it no work. Code: href="index2.php?q=4&id=+document.theForm.lists.value+&picklist" I need to learn how to clear form fields when a user clicks on them. Here is the site in question: http://www.yourvancouvermortgagebroker.ca/apply They used to work, but then I changed the field value and now it doesn't work on some of the fields (whichever ones I changed). Here is a link to the .js file: http://www.yourvancouvermortgagebroker.ca/js/apply.js Is there a way to give an input or textarea field the focus and set the focus to begin right at the end of the current text in the field?
function checkValidFormInput() { if (document.getElementsByName('customerName').value != '') { document.getElementById('customerNameImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerNameImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } if (document.getElementsByName('customerEmail').length > 0) { document.getElementById('customerEmailImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerEmailImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } } I have a form which has various fields which are arrays (so the name of a field may be myField[]). The reason for this is that the form has add buttons to add another field or fields for the purpose of entering another email address, etc., to send invitations and do other things. The problem that I am running into is how to access the individual fields in an array of fields inside javascript to do form validation. So if I have an email address field name emailAddress[], and using the add button, the user of my site adds 3 other copies of the emailAddress[] field, I want to then do form validation onSubmit to ensure those email address are valid using standard procedures. However, inside the javascript code, how do I access the individual fields that make up emailAddress[]? I just cannot find anywhere online the proper way to get at these values. If anyone can help me, I would greatly appreciate it. Happy Holidays Hi there, I have a html form, and I need it so that when a user clicks a button, it adds a field into the form. I also need it to write <td></td> around the new field, and I need it to write this in a specific part row of a table. How would I go about doing this? I've tried searching for the past two hours, but no luck. Many thanks, I appreciate it, Jason Hi! I use the :: Form field Progress Bar from DynamicDrive: Form field Progress Bar Now I trided to change the text when the textarea is full "Limit:100%" to "Your max. characters is reached" I trided it but with no luck. This is the main code.. Code: <script type="text/JavaScript"> function textCounter1(field,counter,maxlimit,linecounter) { // text width// var fieldWidth = 137; var charcnt = field.value.length; // trim the extra text if (charcnt > maxlimit) { field.value = field.value.substring(0, maxlimit); } else { // progress bar percentage var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ; document.getElementById(counter).style.width = parseInt((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" // color correction on style from CCFFF -> CC0000 setcolor(document.getElementById(counter),percentage,"background-color"); } } function setcolor(obj,percentage,prop){ obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)"; } </script> This is the place where the text is set. Code: ((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" Help would be highly appreciated ! greetings Jardin Hi all, I have a couple of functions, an add error function, if some validation is not met I add a message to a array holding error messages and mark the field red, I have no problem with that piece of code... Code: function addError(errorArray, formObj, message) { errorArray[errorArray.length] = message; if (formObj.options != undefined) { formObj.parentNode.className = "error-field"; } else { formObj.className = "error-field"; } } However I have an issue with the 2nd function, it takes in 2 variables, an id for a div which is displaying the error messages, and the form object, the issue I have is removing the error class. for some reason obj.className = '' fails to remove the class, getting the same object using getElementById() (name and id are the same) however if I construct the removing piece of js code as a String and execute it using eval it works... Code: function clearErrors(errorDivId, vForm) { var errorDiv = document.getElementById(errorDivId); errorDiv.innerHTML = ""; errorDiv.style.display = "none"; // remove red boxes for (i=0; i<vForm.elements.length; i++) { var obj = vForm.elements[i]; if (obj.type != "button" && obj.type != "hidden") { if (obj.options != undefined) { if (obj.parentNode.className == "error-field") { obj.parentNode.className = ""; } } else { if (obj.className == "error-field") { alert(obj.name); obj.className == ""; alert(obj.className); obj = document.getElementById(obj.name); alert(obj); obj.className == ""; alert(obj.className); var jsExecuteCommand = "vForm." + obj.name + ".className = '';"; alert(jsExecuteCommand); eval(jsExecuteCommand); alert(obj.className); } } } } } I am so baffled? I have no idea why it won't work can anybody please explain what is happening please? Although I have a work around, I have been banging my head to get to this workaround and I just don't understand why the obj.className = ''; doesn't work. Thanks, Dale |