JavaScript - Refilling Form Fields After Losing Mouse Focus
Hi All,
In my work here there is an application that has recently had a plugin coded up for it, the plugin allows custom message boxes to be opened up by the user when they roll on the help icons. The boxes open automatically and then close as soon as the mouse focus rolls off their box area. The boxes support java script content and html etc so can be very customised. I have coded a user form with various data capture fields. I would like the data in the fields to be reloaded if the user accidentally rolls off the box (as this will close it and the behavious cannot be changed :-<) I have used cookies and tested in browser and all the retreival and storage of the cookie data works fine. Problem is with this plugin app is that i cannot fit in the call to 'onload CheckForCookies()' anywhere - The boxes do not seem to appear as 'window opening events' so could anybody suggest a way of Adding the call to checkforcookies() into my form loading - that does not depend on a window opening event? There are four or five fields and i would like them all to update with whatever was last in them when the messagebox opens - it is not an api/ browser generated messge box, rather it is a custom web widget of some sort and i do not have access to the source code at this time. It is equally important to be able to create or refresh the cookie data for the fields when the user rolls off the box so they do not lose whatever info was typed in so far so i need to call like 'onunload SetAllCookies' Like i say i have the code to do the work, the problem is the functions are not being called as the behaviour of the little boxes does not trigger them as load / unload eventrs. I tested using 'onfocus' and this works but is nbo good as the user would only see the data they had 'lost' when they click on a field. Similar TutorialsExists there anyway to prevent a textarea loosing focus when you press tab? And if yes, could you please determine me how to do this? :P
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?
I wish to have a form clear the default text from my form and allow the user to type in the field but if they move to another fields and do not enter anything in that fields they first went in to the fields restores to the default tetx that was in there before. i have name: tel: state: in the fields by default. i have heard this should be done using javascript can someone help me out here with some coding. i have tried to find it but only find ones that use on focus and for only one fields not multiple Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <form name="form1" method="post" action=""> <input name="name" type="text" id="name" value="Name: "> <br> <br> <input name="email" type="text" id="email" value="Email: "> <br> <br> <textarea name="message" id="message">message: </textarea> <br><br> <input name="submit" type="submit" value="Submit"> <input name="" type="reset"> </form> </body> </html> Hi I'm banging my head against this problem and I'd really appreciate some help. I think the problem is cause by my lack of understanding of how the browser (firefox 3.6.3) handles focus. A simplified version of my problem is: I've defined the function Code: function two_focus() { document.getElementById("two").blur(); alert("hello"); } then in the body I have the form with two text boxes Code: <input id="one" type="text"><input id="two" type="text" onfocus="two_focus();"> When the page is loaded and I click in the second textbox I get the alert, all well and good. I OK the alert box, but when I click on box 1, or anywhere on the page for that matter, the function is called and the alert comes up. I just don't understand why the focus is being returned to the second box when I click anywhere in the browser window. Any comments will be gratefully received. Hi all, Please keep in mind: this is the first code I have ever written -- much of it with help from this forum and the skeleton from other corners of the JS community. Thanks! But now for the problem... I'm developing am income tax calculator, and everything is going swell. Currently the user can type in their adjusted gross income (AGI), hit submit, and learn the amount of income tax they would pay, their tax rate, and their income after tax. I've played around with the events to get the submit button to work in FF, IE, Chrome and Safari -- and I've gotten the enter button to work before with some stock code, but here's the catch: when the user presses enter, i want the focus to leave the input box. I don't care where it goes (submit button, I suppose?) but i need it to leave the input field so the onfocus="clearText(this);" event can fire when they return to type in a new income. Any ideas? Thanks in advance. Code: <script language="javascript" type="text/javascript"> function TotalGrossPerYear() { var Calc = document.NetIncome; if (Calc.InputRad[0].checked) { if ((Calc.AGI.value > 500000)) { Bracket3(); } if ((Calc.AGI.value > 200000 ) && (Calc.AGI.value <= 500000)) { Bracket1(); } if ((Calc.AGI.value <= 200000)) { Bracket2(); } } else if (Calc.InputRad[1].checked) { if ((Calc.AGI.value > 1000000)) { Bracket3(); } if ((Calc.AGI.value > 400000 ) && (Calc.AGI.value <= 1000000)) { Bracket1(); } if ((Calc.AGI.value <= 400000)) { Bracket2(); } } } function Bracket1() { var Calc = document.NetIncome; if (Calc.InputRad[0].checked) { Calc.TaxableIncome.value = (parseFloat(Calc.AGI.value) - 200000) ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) * 0.05)) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } else { if (Calc.InputRad[1].checked) { Calc.TaxableIncome.value = (parseFloat(Calc.AGI.value) - 400000) ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) * .05)) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } } } function Bracket2() { var Calc = document.NetIncome; if (Calc.InputRad[0].checked) { Calc.TaxableIncome.value = 0 ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) * 0.05)) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } else { if (Calc.InputRad[1].checked) { Calc.TaxableIncome.value = 0 ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) * 0.05)) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } } } function Bracket3() { var Calc = document.NetIncome; if (Calc.InputRad[0].checked) { Calc.TaxableIncome.value = (parseFloat(Calc.AGI.value) - 200000) ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) - 300000) * 0.09) + (300000 * 0.05) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } else { if (Calc.InputRad[1].checked) { Calc.TaxableIncome.value = (parseFloat(Calc.AGI.value) - 400000) ; Calc.AmtDue.value = Math.round((parseFloat(Calc.TaxableIncome.value) - 600000) * .09) + (600000 * 0.05) ; Calc.AmtLeft.value = (parseFloat(Calc.AGI.value) - parseFloat(Calc.AmtDue.value)) ; Calc.TaxRate.value = (parseFloat(Calc.AmtDue.value) / parseFloat(Calc.AGI.value) * 100).toFixed(2) + " %"; } } } function Couple() { var Calc = document.NetIncome; Calc.AGI.value = ""; Calc.TaxableIncome.value = "--------"; Calc.AmtDue.value = "--------"; Calc.AmtLeft.value = "--------"; Calc.TaxRate.value = "--------"; } function Individual() { var Calc = document.NetIncome; Calc.AGI.value = ""; Calc.TaxableIncome.value = "--------"; Calc.AmtDue.value = "--------"; Calc.AmtLeft.value = "--------"; Calc.TaxRate.value = "--------"; } function clearText(thefield){ if (thefield.value==thefield.value) thefield.value = "" } </script> </head> and the html... Code: <body> <form name=NetIncome> <table border=5> <th align=left> <ol> <li>Select Individual or Joint filing status. <li>Enter your Adjusted Gross Income. <li>Submit to calculate. <li>Please reset after each calculation. </ol> </th> <tr> <td><font size=5><input type=radio name=InputRad value=PerHour onclick="Individual()"><u>Individual</u> <input type=radio name=InputRad value=PerYear onclick="Couple()"><u>Joint</u></font></td> </tr> <tr><td><input type=text name=AGI size=30 id="txtExamplethree" onfocus="clearText(this);" onsubmit="TotalGrossPerYear();" onblur="this.value=this.value.replace(/[^\d\.]/g, '');" value="Select filing status" maxlength="20" />Adjusted Gross Income </td></tr> <tr><td><input type=text name=TaxableIncome id="txtExampletwo" readonly="readonly" size=30 value="">Taxable Income</td></tr> <tr><td><input type=text name=AmtDue id="txtExampleone" size=30 readonly="readonly" value="">Amount Due in Taxes</font></td></tr> <tr><td><input type=text name=AmtLeft id="txtExample" size=30 readoanly="readonly" value="">Income after Tax</font></td></tr> <tr><td><input type=text name=TaxRate size=10 readonly="readonly">Tax Rate</td></tr> <tr><td align=center><input type="button" value="Submit" onfocus="TotalGrossPerYear(); formatNumber(); formatNumberone(); formatNumbertwo(); formatNumberthree();" /><input type=reset value="Reset Form"></td></tr> </table> </form> Hi, I have a working contact form with 3 of the fields requiring validation and they work well. I have added extra fields to the form (StatusClass, Project, CameFrom). These 3 fields return fine but I need to validated them. My problem is that the new fields don't show in the behaviours/validate panel even though they are within the form tag. Can anyone give me any help and advice as to how to accomplish this? Many thanks Code below.... Code: <script type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script > Code: <form action="contact_us.asp" method="post" name="contact" target="_parent" class="contentText" id="contact" onsubmit="MM_validateForm('FullName','','R','Telephone','','RisNum','Email','','RisEmail');return document.MM_returnValue"> <table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="54%" class="subHeader">Full Name* </td> <td width="46%" class="subHeader"><input name="FullName" type="text" id="FullName" /></td> </tr> <tr> <td class="subHeader">Company Name </td> <td class="subHeader"><input name="CompanyName" type="text" id="CompanyName" /></td> </tr> <tr> <td class="subHeader">Address</td> <td class="subHeader"><input name="Address1" type="text" id="Address1" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address2" type="text" id="Address2" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address3" type="text" id="Address3" /></td> </tr> <tr> <td class="subHeader">Postcode</td> <td class="subHeader"><input name="Postcode" type="text" id="Postcode" /></td> </tr> <tr> <td class="subHeader">Telephone Number* </td> <td class="subHeader"><input name="Telephone" type="text" id="Telephone" /></td> </tr> <tr> <td class="subHeader">Mobile Number </td> <td class="subHeader"><input name="Mobile" type="text" id="Mobile" /></td> </tr> <tr> <td height="25" class="subHeader">Email Address* </td> <td class="subHeader"><input name="Email" type="text" id="Email" /></td> </tr> <tr> <td height="30" class="subHeader">Status*</td> <td class="subHeader"><select name="StatusClass" id="StatusClass"> <option selected="selected">Please Choose</option> <option>Architect</option> <option>Interior Designer</option> <option>Private Client</option> <option>Student</option> <option>Trade Enquiry</option> </select> </td> </tr> <tr> <td height="23" class="subHeader">Project*</td> <td class="subHeader"><select name="Project" size="1" id="Project"> <option selected="selected">Please Choose</option> <option>Planning Stages</option> <option>New Build</option> <option>Refurbishment</option> <option>Barn Conversion</option> <option>No project - information only</option> </select> </td> </tr> <tr> <td height="37" class="subHeader">How did you hear about us?*</td> <td class="subHeader"><select name="CameFrom" size="1" id="CameFrom"> <option selected="selected">Please Choose</option> <option>Web Search</option> <option>Grand Designs</option> <option>Living Etc</option> <option>Home Building & Renovation</option> <option>Architect</option> <option>Friend/Family</option> <option>Magazine/Editorial</option> <option>Newspaper Article</option> <option>Trade Show/Exhibition</option> <option>Other</option> </select></td> </tr> <tr> <td height="24" class="subHeader">Brochure Request </td> <td class="subHeader"><input name="Brochure" type="checkbox" id="Brochure" value="checkbox" /></td> </tr> <tr> <td class="subHeader">Message</td> <td class="subHeader"><span class="style4"> <textarea name="Message" id="Message"></textarea> </span></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Submit" type="submit" value="Submit" /></td> </tr> <tr> <td colspan="2" class="subHeader"><em>* Required fields</em></td> </tr> </table> </form> Hi; I'd like to ask you a question; why my mouse cursor does not sit in the position of the leftmost and topmost of a bbcode form. Thanks. my form as following; bbcode form PHP Code: <form action="story_verify1.php" method="post" name="editform" onsubmit="return checkForm(this)"> <table id="editform"> <tr> <td id="story">My story</td> </tr> <tr> <td> <input type="button" class="button" value="bold" name="bold" onclick="javascript:tag('b', '[b]', 'bold*', '[/b]', 'bold', 'bold');" onmouseover="helpline('bold')" /> <input type="button" class="button" value="italic" name="italic" onclick="javascript:tag('i', '[i]', 'italic*', '[/i]', 'italic', 'italic');" onmouseover="helpline('italic')" /> <input type="button" class="button" value="underline" name="underline" onclick="javascript:tag('u', '[u]', 'underline*', '[/u]', 'underline', 'underline');" onmouseover="helpline('underline')" /> <input type="button" class="button" value="quote" name="quote" onclick="javascript:tag('q', '[quote]', 'quote*', '[/quote]', 'quote', 'quote');" onmouseover="helpline('quote')" /> <input type="button" class="button" value="code" name="code" onclick="javascript:tag('c', '[code]', 'code*', '[/code]', 'code', 'code');" onmouseover="helpline('code')" /> <input type="button" class="button" value="url" name="url" onclick="javascript:tag('url', '[url]', 'url*', '[/url]', 'url', 'url');" onmouseover="helpline('url')" /> <input type="button" class="button" value="img" name="img" onclick="javascript:tag('img', '[img]', 'img*', '[/img]', 'img', 'img');" onmouseover="helpline('img')" /> <br /> Font size: <select name="fontsize" onchange="font('[size=' + this.form.fontsize.options[this.form.fontsize.selectedIndex].value + ']', '[/size]'); this.selectedIndex=2;" onmouseover="helpline('fontsize')" class="form_elements_dropdown"> <option value="50%" >Tiny</option> <option value="75%" >Small</option> <option value="100%" selected="selected" >Normal</option> <option value="150%" >Large</option> <option value="200%" >Huge</option> </select> Font color: <select name="fontcolor" onchange="font('[color=' + this.form.fontcolor.options[this.form.fontcolor.selectedIndex].value + ']', '[/color]'); this.selectedIndex=0;" onmouseover="helpline('fontcolor')" class="form_elements_dropdown" > <option value="black" style="color:black">Black</option> <option value="silver" style="color:silver">Silver</option> <option value="gray" style="color:gray">Gray</option> <option value="maroon" style="color:maroon">Maroon</option> <option value="red" style="color:red">Red</option> <option value="purple" style="color:purple">Purple</option> <option value="fuchsia" style="color:fuchsia">Fuchsia</option> <option value="navy" style="color:navy">Navy</option> <option value="blue" style="color:blue">Blue</option> <option value="aqua" style="color:aqua">Aqua</option> <option value="teal" style="color:teal">Teal</option> <option value="lime" style="color:lime">Lime</option> <option value="green" style="color:green">Green</option> <option value="olive" style="color:olive">Olive</option> <option value="yellow" style="color:yellow">Yellow</option> <option value="white" style="color:white">White</option> </select> <br /> <input type="text" name="helpbox" size="75" class="helpbox" readonly="readonly"/> </td> </tr> <tr> <td> Post:***<br /> <textarea rows="10" cols="50" name="Content" class="form_elements_text" id="thread"> <?php echo trim(stripslashes($_SESSION['story_content'])); ?> </textarea> </td> </tr> <tr> <td colspan="2" class="security_check"> <?php $_SESSION['fvalue']=rand(0,9); echo $_SESSION['fvalue']; ?> + <?php $_SESSION['svalue']=rand(0,9); echo $_SESSION['svalue']; ?> = <input type="text" name="result" /> ** </td> </tr> <tr> <td colspan="2" id="post"> <input type="submit" name="Post" value="Post" class="button" /> <input type="submit" name="preview" value="Preview" class="button"/> <input type="reset" value="Reset" class="button" onclick="javascript:confirm_reset();"/> </td> </tr> </table> </form> bbcode.js PHP Code: //Variables for controlling opening and closing tags (function tag) var b = 2; var i = 2; var u = 2; var q = 2; var mail = 2; var url = 2; var img = 2; //Function for creating non-font tags function tag(v, tagadd, newbut, tagclose, oldbut, name) { var r = document.selection.createRange().text; rr = tagadd + r + tagclose; if(r) { document.selection.createRange().text = rr; } else { if (eval(v)%2 == 0) { eval("window.document.editform."+name+".value = newbut;"); var content = window.document.editform.content.value; window.document.editform.content.value = content + tagadd; window.document.editform.content.focus(); } else { eval("window.document.editform."+name+".value = oldbut;"); var content = window.document.editform.content.value; window.document.editform.content.value = content + tagclose; window.document.editform.content.focus(); } eval(v+"++;"); } } //Function for adding font color and size tags function font(bbopen, bbclose) { var r = document.selection.createRange().text; rr = bbopen + r + bbclose; if(r) { document.selection.createRange().text = rr; }else{ var post = document.editform.post; post.value += bbopen +r+ bbclose; post.focus(); } return; } function smilie (tag) { var myField; tag = ' ' + tag + ' '; if (document.getElementById('thread') && document.getElementById('thread').type == 'textarea') { myField = document.getElementById('thread'); } else { return false; } if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = tag; myField.focus(); } else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; var cursorPos = endPos; myField.value = myField.value.substring(0, startPos) + tag + myField.value.substring(endPos, myField.value.length); cursorPos += tag.length; myField.focus(); myField.selectionStart = cursorPos; myField.selectionEnd = cursorPos; } else { myField.value += tag; myField.focus(); } } //Helpbox messages bold_help = "Bold text: [b]text[/b]"; italic_help = "Italic text: [i]text[/i]"; underline_help = "Underline text: [u]text[/u]"; quote_help = "Quote text: [quote]text[/quote] or [quote=name]text[/quote]"; code_help = "Code display: [code]code[/code]"; img_help = "Insert image: [img]http://image_url[/img]"; url_help = "Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url]"; fontcolor_help = "Font color: [color=red]text[/color] Tip: you can also use color=#FF0000"; fontsize_help = "Font size: [size=50%]small text[/size]"; //Function for displaying help information // Shows the help messages in the helpline window function helpline(help) { var helpbox = document.editform.helpbox; helpbox.value = eval(help + "_help"); } //Function to confirm reset function confirm_reset () { if(confirm("If you continue you will loose everything you have entered so far. \n \n" + "Click OK to proceed and start again. \n \n Alternatively click cancel to continue " + "working on your post.")) { return true; } else { return false; } } //Check the form submission for errors function checkForm() { var subject = document.editform.subject; var post = document.editform.post; //Check to make sure post lengths are sensible if (subject.value.length < 2 && post.value.length < 2) { alert("This is a short post!" + " \n \n " + "We require that each post (and subject) \n" + "be at least 2 characters long. \n \n" + "Go back and try again."); return false; } else { if (subject.value.length < 2) { alert("We require that the subject \n" + "be at least 2 characters long. \n \n" + "Go back and try again."); return false; } else { if (post.value.length < 2) { alert("We require that each post \n" + "be at least 2 characters long. \n \n" + "Go back and try again."); return false; } else { return true; } } } } I've got to have a typo somewhere, but i can't seem to find it. I need a new pair of eyes to point it out for me. background: trying to code a mouseover link for a nav bar. everything is working( hyperlink, normal image shows up) but when i mouse over the image swap doesn't happen. I have 2 parts of code. 1st preloads images and does the swap function. loads in <head> See below: Code: <SCRIPT language="javascript" type="text/javascript"> if (document.images) { /* preload images */ var subcontractorsOn = new Image (); subcontractorsOn.scr = "subcontractorsOn.gif"; var subcontractorsOff = new Image (); subcontractorsOff.scr = "subcontractorsOff.gif"; } function mouseOn (imgName) { if (document.images) document [imgName].scr = eval (imgName + "On.scr"); } function mouseOff (imgName) { if (document.images) document [imgName].scr = eval (imgName + "Off.scr"); } </SCRIPT> 2nd just calls the functions to preform the swap. this is in the <body> see code below Code: <a href="subcontractors.htm" onMouseOut="mouseOn('subcontractors')" onMouseOver="mouseOff('subcontractors')"> <img src="subcontractorsOff.gif" height="40" width="133" name="subcontractors" id="subcontractors" border="0" alt="subcontractors"></a> any insight would be great. regards, Fatmann66 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); ?> Hi all, I'm new to here and JS but I have question for you! So I have this form with inputs that are considered arrays in my PHP code: Code: <input type="checkbox" name="1" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="2" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="3" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="4" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="5" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="6" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="7" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="8" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="9" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="10" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="11" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="12" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="13" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="14" /> <input name="ii[]" type="text"> <br /> <input type="checkbox" name="15" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="16" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="17" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="18" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="19" /> <input name="i[]" type="text"> <br /> <input type="checkbox" name="20" /> <input name="i[]" type="text"> <br /> I don't want to keep adding in new spots every time a user want to add a new field. I would like them to be able to press a button that will add another one of those fields and so on. I'm not sure how this can be achieved but that's why I am turning to you! Thanks! Hi, i have this code that generate 10 rows with form fields: Code: <form> <?php for($i=1;$i<=10;$i++) {?> <div id="rowz-rep"> <div class="row1"><?=$i?></div> <div class="row2a"><input name="title[]" type="text" class="fieldSubmit"/></div> <div class="row3a"><input name="url[]" type="text" class="fieldSubmit"/></div> <div class="row4a"><select name="type[]" class="dropSubmit"><? foreach($allowed_types as $at) { echo '<option value="'.$at.'">'.$at.'</option>'; }?></select></div> </div> <? }?> </form> I need that onclick with JS add 10 more rows so i get something like Code: <?php for($i=1;$i<=20;$i++) {?> 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> Here's what I have so far in my validation part. However, I need help as to how to validate the following fields when the user clicks the submit button. -Radio Button *title (4 options) *member (3 options) *vegetarian (2 options) -Drop down lists *regstartdate (3 options) *regenddate (3 options) *confdinner (2 options) *paymethod (3 options) -UK Post Code (text box with maxlength=8) My current code shows 1 popup with all the error messages. Here's what I have so far: Redacted I have a drop down selection where it shows and hides form inputs depending on selection. When the page loads it shows the drop down selections with no form inputs. After user selects drop down it shows the form fields. It works great but I want it to show the same form fields after the user hits the submit button which submits the page to itself. It currenlty goes back to the default selection list and doesnt show any of the form fields. Basically it hides all the form fields after the user hits submit button. How do I make it keep the last shown form fields after the user hits the submit button? test3.html looks like this: Code: <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Show/Hide</title> <script type="text/javascript"> function display(obj,id1,id2) { txt = obj.options[obj.selectedIndex].value; document.getElementById(id1).style.display = 'none'; document.getElementById(id2).style.display = 'none'; if ( txt.match(id1) ) { document.getElementById(id1).style.display = 'block'; } if ( txt.match(id2) ) { document.getElementById(id2).style.display = 'block'; } } </script> </head> <body> <form name="tester" action="test3.html" method="get"> <table width="340" cellspacing="0" cellpadding="2"> <thead> <tr> <td class="title">Type:</td> <td class="field"> <select name="type" onchange="display(this,'text','image');"> <option>Please select:</option> <option value="image">Image</option> <option value="text">Texts</option> <option value="invisible">Invisible</option> </select> </td> </tr> </thead> <tfoot> <tr> <td class="align-center" colspan="2"><input type="submit" name="submit" value="Update" /> <input type="reset" value="Reset" /></td> </tr> </tfoot> <tbody id="text" style="display: none;"> <tr> <td class="title">Text Color:</td> <td class="field"><input type="text" name="color" size="8" maxlength="7" /></td> </tr> </tbody> <tbody id="image" style="display: none;"> <tr> <td class="title">Image:</td> <td class="field"><input type="file" name="image" size="10" /></td> </tr> <tr> <td class="title">X Coordinates:</td> <td class="field"><input type="text" name="x_coordinates" size="5" /></td> </tr> <tr> <td class="title">Y Coordinates:</td> <td class="field"><input type="text" name="y_coordinates" size="5" /></td> </tr> <tr> <td class="title">Text Color:</td> <td class="field"><input type="text" name="color" size="8" maxlength="7" /></td> </tr> </tbody> <tbody> <tr> <td class="title">Display:</td> <td class="field"> <select name="display"> <option value="visitors">Visitors</option> <option value="hits">Hits</option> </select> </td> </tr> </tbody> </table> </form> </body> </html> I have two slightly different forms on the same page, but I want the values in form1 to auto populate the same form fields in form2. 1 field is a text field, the rest are drop down menus. How would I accomplish this? Link to tutorial would be much appreciated. Thanks
So, I'm trying to make a function that marks a specific form field if it triggers an error when the form submits. Doesn't seem to work, though. The function to mark the form field resides in a .js file separate from the function that validates the form. Not sure if that matters, but thought I'd post it here just to be sure. Here's the code for the field marking script: Code: function markFormField(fieldInError) { // start by changing its background color fieldInError.style.backgroundColor = "#FF99FF"; // check the parent tag to make sure it's a label if (fieldInError.parentNode.tagName == "LABEL") { // if it is, change the font color fieldInError.parentNode.style.color = "#FF0000"; } } Here's the code that validates the form: Code: function checkNewsInput() { // see if the DOM can be used if (!document.getElementById) return; // otherwise, set up the variables var newsCat = document.getElementById("category"); var newsTitle = document.getElementById("title"); var newsBody = document.getElementById("body"); var newsDesc = document.getElementById("desc"); var newsTags = document.getElementById("tags"); var newsInfo = document.getElementById("info"); var newsPwd = document.getElementById("pwd"); /* NOTE: cursorToEnd is a function I got from a helpful member of this forum. Its code is not listed in this post. */ if (newsCat.value == "") { window.alert("Please select a category."); return false; markFormField(newsCat); } else if (newsTitle.value.length < 5 || newsTitle.value == "") { window.alert("The title must be at least 5 characters in length."); return false; markFormField(newsTitle); cursorToEnd(newsTitle); } else if (newsBody.value.length < 10 || newsBody.value == "") { window.alert("The body of the post must be at least 10 characters in length."); return false; markFormField(newsBody); cursorToEnd(newsBody); } else if (newsDesc.value.length < 10 || newsDesc.value == "") { window.alert("The description must be at least 10 characters in length."); return false; markFormField(newsDesc); cursorToEnd(newsDesc); } else if (newsTags.value.length < 5 || newsTags.value == "") { window.alert("The tags field must be at least 5 characters in length."); return false; markFormField(newsTags); cursorToEnd(newsTags); } else if (newsInfo.value.length < 10 || newsInfo.value == "") { window.alert("The info must be at least 10 characters in length."); return false; markFormField(newsInfo); cursorToEnd(newsInfo); } else if (newsPwd.value == "") { window.alert("Please enter your password."); return false; markFormField(newsPwd); cursorToEnd(newsPwd); } else { // all is good, so let the form submit return true; } } 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 This is what I'm trying to do. CONDITIONS: If a person selects a Friday Class but not a Saturday Class the Total Cost Field will automatically enter $99. If a person selects a Saturday Class but not a Friday Class the Total Cost Field will automatically enter $99 as well. If a person selects both a Friday & Saturday Class the Total Cost field will automatically be $159. I found the following code and so far only have it changing when a Friday class is entered. I have no idea where to go from here. Please help. Code: <!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" xml:lang="en" lang="en"> <head> <title>Test</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> </head> <body> <div> <p><span class="style1">Friday Class:</span> <select id="fridayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> <p> <span class="style1">Saturday Class:</span> <select id="saturdayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> </div> <div><span class="style1">Total Cost:</span> <input type="text" id="totalCost"/></div> <script> window.onload = function () { var friday = document.getElementById('fridayClass'), saturday = document.getElementById('saturdayClass'); friday.onchange = function () { totalCost.value = '$99.00'; }; }; </script> Hi all! I have a form which has some checkboxes and the name of every checkbox is email_(a counting number) . Lets say I have no access to the counting number because it is changed every time the page reloads. How can i create a script to return how many email_ checkboxes is in the form? Code: <script> // here i want a script to count how many checkboxes is in the form. // </script> <form> <script> counter = 2 // I dont have access to this number because it is changing every time I reload the page. for(i=0;i<counter;i++) { test.innerHTML += "<input type='checkbox' value='' name='email_"+i+"'>"; } </script> <div id="test"></div> </form> please help! Greetings experts, this is my first time here. So, please take easy on me. I have makup with 2 sections. The first section contains 5 form fields and are required. The second second has 2 form fields and are optional. Users can only choose from one section or the other but not both. The js script below ensures that if users select from section 2, section one will not challenge for validation and works a treat. The challenge I have now is to ensure that if users choose from section 1, the 2 form fields in section are automatically disabled so they won't be attempted to choose from it. Similarly, if users select from section 2, all form fields in section one are automatically disabled so they won't be tempted to choose from that section. Is this possible? If not possible, is it possible to raise an error? For instance, a user selects from section 1 and attempts to select from any of the 2 form fields in section 2, a message that says, "You can only select from one section but from both. Similarly if a user selects from section 2 first, same thing happens. Thanks very much for your assistance. function validate() { if(document.getElementById("<%=txtrequest.ClientID%>").value != "" && document.getElementById("<%=txtreceived.ClientID %>").value != "") { if (document.getElementById("<%=txtName.ClientID%>").value == "") { alert("Please enter name"); document.getElementById("<%=txtName.ClientID%>").focus(); return false; } if (document.getElementById("<%=txtCity.ClientID %>").value == "") { alert("Please enter city"); document.getElementById("<%=txtCity.ClientID %>").focus(); return false; } if (document.getElementById("<%=txtState.ClientID%>").value == "") { alert("Please enter state"); document.getElementById("<%=txtState.ClientID%>").focus(); return false; } if (document.getElementById("<%=txtZip.ClientID%>").value == "") { alert("Please enter zip"); document.getElementById("<%=txtZip.ClientID%>").focus(); return false; } if (checkradio() == false) { alert("Please enter contacts"); document.getElementById("<%=txtContacts.ClientID%>").focus(); return false; } } return true; } |