JavaScript - How To Put A Form Within A Function?
Hi!
First of, I want to say that I don't have a lot of knowledge with js, so please bare with me. I have this function: Code: function formFunction() { return new LightFace({ title: $('demo1title').value, content: $('demo1content').value, draggable: true }).open(); } It is a part of a code that displays a small on-page window. However, within that code I want to have a form that posts $('demo1title').value as a hidden value. Any idea how to do this? Similar TutorialsI have the following form working with on onsumbit function, but I would like to change it so that instead of having to click the purchase button to see total price, you only have to change the quanity text box input. I would welcome any help. I just can not seem to get it to work. Code: <script language="javascript" type="text/javascript"> function checkQuantity(frm) { var succesful = false; var numQuantity; numQuantity = parseInt(frm.Quantity.value); var numTotalPrice; if (numQuantity != 0) { numTotalPrice = numQuantity * 4; frm.TotalPrice.value = numTotalPrice; //new String(numTotalPrice); successful = true; } else { alert("Sorry must order more than 0"); successful = false; } return succesful; } </script> Code: <form action="" onsubmit="return checkQuantity(this)" style="width: 193px"> <table cellpadding="4" style="width:111%"> <tr> <td class="style1"> Quanity:</td> <td class="formInputCell"> <input name="Quantity" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style1"> Total Price $ </td> <td class="formInputCell"> <input name="TotalPrice" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style2"></td> <td><input id="Submit1" type="submit" value="Buy Now" class="buttonstyle" /></td> </tr> </table> </form> The below script keeps a running total dollar tab. It uses the "name" of the elements but I would like it to use the "ID" instead. Can somebody pretty please adjust the function to look at the id. I've changed the first 2 form elements to id. Tracy Code: <script language="JavaScript" type="text/javascript"> <!-- function CalculateTotal(frm) { var order_total = 0 // Run through all the form fields for (var i=0; i < frm.elements.length; ++i) { // Get the current field form_field = frm.elements[i] // Get the field's name form_name = form_field.name // Is it a "product" field? if (form_name.substring(0,4) == "PROD") { // If so, extract the price from the name item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1)) // Get the quantity item_quantity = parseInt(form_field.value) // Update the order total if (item_quantity >= 0) { order_total += item_quantity * item_price } } } // Display the total rounded to two decimal places frm.TOTAL.value = round_decimals(order_total, 2) } function round_decimals(original_number, decimals) { var result1 = original_number * Math.pow(10, decimals) var result2 = Math.round(result1) var result3 = result2 / Math.pow(10, decimals) return pad_with_zeros(result3, decimals) } function pad_with_zeros(rounded_value, decimal_places) { // Convert the number to a string var value_string = rounded_value.toString() // Locate the decimal point var decimal_location = value_string.indexOf(".") // Is there a decimal point? if (decimal_location == -1) { // If no, then all decimal places will be padded with 0s decimal_part_length = 0 // If decimal_places is greater than zero, tack on a decimal point value_string += decimal_places > 0 ? "." : "" } else { // If yes, then only the extra decimal places will be padded with 0s decimal_part_length = value_string.length - decimal_location - 1 } // Calculate the number of decimal places that need to be padded with 0s var pad_total = decimal_places - decimal_part_length if (pad_total > 0) { // Pad the string with 0s for (var counter = 1; counter <= pad_total; counter++) value_string += "0" } return value_string } //--> </script> <FORM> <TABLE BORDER =3> <TR><TD ALIGN="CENTER"><B>Please <BR> enter <BR> quantity:</FONT></TD> <TD ALIGN="CENTER"><B>Description</TD><TD ALIGN="CENTER"><B>Price<BR> (each)</B></TD></TR> <TR> <TD ALIGN="CENTER"><INPUT TYPE=TEXT ID="PROD_SP_4.99" SIZE=3 MAXLENGTH=3 onkeyup="CalculateTotal(this.form)"></TD><TD>Spelt Bread 24 oz</TD><TD ALIGN="RIGHT">$4.99</TD> </TR> <TR><TD ALIGN="CENTER"><INPUT TYPE=TEXT ID="PROD_SPMG_4.99" SIZE=3 MAXLENGTH=3 onkeyup="CalculateTotal(this.form)"></TD><TD>Spelt Multi-Grain Bread* 24 oz</TD><TD ALIGN="RIGHT">$4.99</TD> </TR> <TR><TD ALIGN="CENTER"><INPUT TYPE=TEXT NAME="PROD_SPCR_4.99" SIZE=3 MAXLENGTH=3 onkeyup="CalculateTotal(this.form)"></TD><TD>Spelt Cinnamon-Raisin Bread 24 oz</TD><TD ALIGN="RIGHT">$4.99</TD> </TR> <TR><TD ALIGN="CENTER"><INPUT TYPE=TEXT NAME="PROD_SW_3.99" SIZE=3 MAXLENGTH=3 onkeyup="CalculateTotal(this.form)"></TD><TD>Spelt White Bread* 18 oz</TD><TD ALIGN="RIGHT">$3.99</TD> </TR> <TD>TOTAL</TD> <TD ALIGN="RIGHT"><INPUT TYPE=TEXT NAME=TOTAL SIZE=10 onFocus="this.form.elements[0].focus()"></TD> </TABLE> <P> </FORM> I am trying to create a form that writes text to an HTML canvas when submitted. Eventually, the function that writes the text will be more complex. The problem is the text only appears briefly, because the function is only called once when the form is submitted. I want the function to be called continuously after the form is submitted. How do I do this? I have had very little experience with JS. A lame (failed) attempt... Code: <html> <head> </head> <body> <canvas id="canvas" width="790" height="605"> Sorry, your browser doesn't support HTML5 </canvas> <form name="frm1" action=" " onsubmit="greeting()"> <input type="text" name="fname" /> </form> </body> <script type="text/javascript"> function init() { //use canvas "canvas" and assign to variable canvas canvas=document.getElementById("canvas"); c=canvas.getContext("2d"); } function greeting() { c.fillText("var!!!", 100, 460); var test = 1; } if (test == 1) { greeting(); } init(); </script> </html> Thanks Newbie developer/sys admin working on a SalesForce platform here, so excuse my ignorance with terminology. This is a file upload problem. The current code first inserts a record into Salesforce, THEN posts to Amazon S3. The record is just a unique URL that is a link to where Amazon houses the file. Problem here is that sometimes users cancel/close the page before form submits, but the record is already created. Now, I need to reverse this so that it first posts to Amazon S3, then inserts the "link" record. Is there a way to evaluate if a post is successful THEN trigger the apex method OR a second javascript function? Relevant bits he (if we need the entire page, i can paste that too, but alot of it is apex and salesforce specific) Code: <script type="text/javascript"> var sendFile = false; var ProgressImage = document.getElementById('{!$Resource.ajaxloader}'); document.getElementById('{!$Component.hiddenServerURL}').value = '{!$Api.Enterprise_Server_URL_140}'; function setFileName(file) { var f = file.replace(/\\/g, ""); f = f.replace(/C\:fakepath/g, ""); <!--Required for IE8--> document.s3Form.key.value = "{!CustomerName}/{!OrderName}/" + f; document.getElementById('{!$Component.fileName}').value = f; suffix = f.lastIndexOf(".") + 1; contentType = f.slice(suffix); document.getElementById('{!$Component.contentType}').value = contentType; } function setFileType(type) { document.getElementById('{!$Component.fileType}').value = type; } function checkFile() { if (document.s3Form.file.value=="") { alert("Please, select a file."); return false; } else if (document.s3Form.fType.value=="--None--") { alert("Please, select a file type."); return false; } else { loadSubmit(); insertFile(); sendFile = true; } } function submitFile() { if(sendFile = false) { return false; } else { document.s3Form.submit(); } } function loadSubmit() { document.getElementById("progress").style.visibility = "visible"; setTimeout(function(){ProgressImage.src = ProgressImage.src},100); return true; } function cancelFile() { window.location.href = "{!$Setup.companyInfo__c.colliers__c}"; } function completeFile() { completeOrder(); } </script> apex:actionFunction on this page, javascript can directly make a call to the class and invoke a method there. Code: <apex:actionFunction name="insertFile" action="{!insertFile}" oncomplete="submitFile();return false;"/> the pertinent "html" (visualforce) for this page Code: <apex:pageBlockButtons location="bottom"> <input class="btn" type="button" value="Upload File" onClick="checkFile();return false;"/> <input class="btn" type="button" value="Cancel" onClick="cancelFile();return false;"/> <input class="btn" type="button" value="Complete Order" onClick="completeFile();return false;"/> </apex:pageBlockButtons> This piece is from the class/extension: Code: //SF File insert on an object (passed from page) public PageReference insertFile() { this.file.Name = fileName; this.file.Type__c = fileType; this.file.Content__c = contentType; insert this.file; return null; } Ideally, i would like to change the checkFile() function to something like the below - but haven't had much luck in researching how to accomplish this... Code: function checkFile() { if (document.s3Form.file.value=="") { alert("Please, select a file."); return false; } else if (document.s3Form.fType.value=="--None--") { alert("Please, select a file type."); return false; } else { loadSubmit(); if(document.seForm.submit() = true) insertFile(); } } UPDATE: I just learned that S3 should return a "success_action_status" if the post is successful - how do i use this to achieve what I need? (http://docs.amazonwebservices.com/Am...POSTForms.html) Okay so this is a homework assignment. I have completed MOST of it. What I am completely lost on is how make the totals show up in the shipping fee section based on what products the user selects. "When the user selects an option from the Hand Tool selection list (and only the Hand Tool selection list) Display $20.00 in the Item 1 text box. Display $0 in the Item 2 text box. Display $5.00 in the Shipping text box. Display $25.00 in the Total text box. When the user selects an option from the Power Tool selection list (and only the Power Tool selection list) Display $0 in the Item 1 text box. Display $30.00 in the Item 2 text box. Display $10.00 in the Shipping text box. Display $40.00 in the Total text box. When the user selects both an option from the Hand Tool selection list and an option from the Power Tool selection list Display $20.00 in the Item 1 text box. Display $30.00 in the Item 2 text box. Display $15.00 in the Shipping text box. Display $65.00 in the Total text box. If the user returns back to the default (the words Hand Tool and Power Tool in the selection list) you must treat that as de-selecting the tool and change the text boxes accordingly." 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> Project 2 </title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="js_styles.css" type="text/css" /> <script type="text/javascript"> /* <![CDATA[ */ function jumpto(x){ if (document.form1.jumpmenu.value != "null") { document.location.href = x } } function checkForNumber(fieldValue) { var numberCheck = isNaN(fieldValue); if (numberCheck == true) { window.alert("You must enter a numeric value!"); return false; } } function confirmSubmit() { if (document.forms[0].first_name.value == "" || document.forms[0].last_name.value =="" || document.forms[0].address_1.value =="" || document.forms[0].city.value =="" || document.forms[0].state.value == "") { window.alert("You have not entered the requested personal information."); return false; } } function confirmReset() { var resetForm = window.confirm("Are you sure you want to reset the form?"); if (resetForm == true) return true; return false; } /* ]]> */ </script> </head> <body> <h2>Purchase Order</h2> <form action="FormProcessor.html" method="get" enctype="application/x-www-form-urlencoded" onsubmit="return confirmSubmit();" onreset="return confirmReset();"> <h3>Products</h3> Hand Tools $20.00 <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option value="$0.00">Hand Tool</option> <option value="$20.00">Saw</option> <option value="$20.00">Hammer</option> <option value="$20.00">Screwdriver</option> <option value="$20.00">Wrench</option> <option value="$20.00">Pliers</option> </select> Power Tool $30.00 <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option value="$0.00">Power Tool</option> <option value="$30.00">Circular Saw</option> <option value="$30.00">Sabre Saw</option> <option value="$30.00">Drill</option> <option value="$30.00">Belt Sander</option> <option value="$30.00">Table Saw</option> </select> <h3>Shipping Fees</h3> <p>Item 1: <input type="text" name="city" size="15" /> Item 2: <input type="text" name="city" size="15" /> Shipping: <input type="text" name="city" size="15" /> Total: <input type="text" name="city" size="15" /> <h3>Customer Information</h3> <p>First Name <input type="text" name="first_name" size="25" value="First Name" onclick="document.forms[0].first_name.value = '';" /> Last Name <input type="text" name="last_name" size="25" value="Last Name" onclick="document.forms[0].last_name.value = '';" /> <p>Street Address 1 <input type="text" name="address_1" size="50" value="Address 1" onclick="document.forms[0].address_1.value = '';" /> <p>City <input type="text" name="city" size="20" value="City" onclick="document.forms[0].city.value = '';" /> State <input type="text" name="state" size="15" value="State" onclick="document.forms[0].state.value = '';" /> Zip <input type="text" name="zip" size="10" value="Zip" onclick="document.forms[0].zip.value = '';" /> <p>Phone <input type="text" name="phone" size="20" value="Phone" onchange="return checkForNumber(this.value)" onclick="document.forms[0].phone.value = '';" /> Fax <input type="text" name="fax" size="20" value="Fax" onchange="return checkForNumber(this.value)" onclick="document.forms[0].fax.value = '';" /> <p>Payment Method? <input type="radio" name="visa" />Visa<input type="radio" name="master_card" />Master Card <input type="radio" name="american_express" />American Express</p> <p>Credit Card Number <input types="text" name="cc_number" size="50" /> <p> Expiration Month: <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option>Month</option> <option value="january">January</option> <option value="february">February</option> <option value="march">March</option> <option value="april">April</option> <option value="may">May</option> <option value="june">June</option> <option value="july">July</option> <option value="august">August</option> <option value="september">September</option> <option value="october">October</option> <option value="november">November</option> <option value="december">December</option> </select> Expiration Year <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option>Year</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> </select> </p> <p><input type="image" alt="Graphical image of a subscribe button" src="subscribe.png" /></p> <p><input type="reset" value="Reset Registration Form" onchange="confirmReset" /></p> </form> <p> <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" style="border: 0px;" /></a> <a href="http://jigsaw.w3.org/css-validator/check/referer"> <img src="http://www.austincc.edu/jscholl/images/vcss.png" alt="Valid CSS!" height="31" width="88" style="border: 0px;" /></a> </p> </body> </html> I'm not looking for someone to complete this for me. I just need some help with how I would write a function for this. Hi, I am quite new to javascript but I'm quite sure this problem is very easy to solve. I have a vague idea of what might be going wrong but I have no idea what I should be doing instead. Here is what I'm trying to do: User inputs X and Y coordinates into form validate that they are numbers do a little bit of maths redirect to a php script with a single variable tacked onto the end of the url Here is the form code: Code: //part of a larger php script to make the form echo "<form name='gotoForm' onsubmit='return coordCalc()'> <fieldset> <legend>Go to Square</legend> X <input type='text' id='X' size='1' maxlength='3'/> Y <input type='text' id='Y' size='1' maxlength='3'/> <input type='submit' value='Go To' /> </fieldset> </form> "; which references these functions in the header: Code: //Is it a number function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } //deal with the input, check if they are both numbers with the above function //if they are do some maths on the input //add the result onto a url and redirect function coordCalc (){ var Xcoord = document.getElementById('X'); var Ycoord = document.getElementById('Y'); if(isNumeric(Xcoord, "Please enter a Number for X")){ if(isNumeric(Ycoord, "Please enter a Number for Y")){ //Takes the X and Y coordinates and transforms them into a single number //not fully coded in case you try putting some numbers into the formula btw :) var X = parseInt(document.getElementById('X').value); var Y = parseInt(document.getElementById('Y').value); var G = 16; var Z = (((G + 1) - Y) - Y); var A = (Y + Z); var B = (X - 1); var L = ((A * (G - 1)) + B); window.location = "map.php?start=" + L; } } return false; } The number validation works but the url ends up as map.php?start=NaN. Now, this simply must be the way I am assigning the Xcoord and Ycoord variables with the document.getElementByID() function I am sure. But like I said, I have no idea what to do instead, any help is massively appreciated. Thankyou! I am trying to create a function or have this work some how where it displays the first number when you make your choice in the first drop down box, which is working so far. In the second drop down box, if any of the answers are chosen except for none, it will take off 10% of the first number. Then add or subtract from there. I just have a problem with creating a function to take off that 10%. Here is the javascript: Code: /* This source is shared under the terms of LGPL 3 www.gnu.org/licenses/lgpl.html You are free to use the code in Commercial or non-commercial projects */ //Set up an associative array //The keys represent the size of the cake //The values represent the cost of the cake i.e A 10" cake cost's $35 var practice_field = new Array(); practice_field["None"]=0; practice_field["Allergy and Immunology"]=4400; practice_field["Endocrinology"]=4400; practice_field["Pathology"]=4400; practice_field["Dermatology"]=4400; practice_field["Geriatrics"]=4400; practice_field["Physical Rehabilitation"]=4400; practice_field["Family Practice"]=6900; practice_field["General Practice"]=6900; practice_field["Internal Medicine"]=6900; practice_field["Oncology"]=6900; practice_field["Oral Surgery"]=6900; practice_field["Radiology"]=6900; practice_field["Gastroenterology"]=6900; practice_field["Infectious Disease"]=6900; practice_field["Nephrology"]=6900; practice_field["Ophthalmology"]=6900; practice_field["Pediatrics"]=6900; practice_field["Urology"]=6900; practice_field["Anesthesiology"]=9000; practice_field["Cosmetic Surgery"]=9000; practice_field["General Surgery"]=9000; practice_field["Neurology"]=9000; practice_field["Otolaryngology"]=9000; practice_field["Plastic Surgery"]=9000; practice_field["Vascular Surgery"]=9000; practice_field["Cardiology"]=9000; practice_field["Emergency Medicine"]=9000; practice_field["Gynecology"]=9000; practice_field["Orthopedic Surgery"]=9000; practice_field["Pain Management"]=9000; practice_field["Pulmonary Surgery"]=9000; practice_field["Neurological Surgery"]=9900; practice_field["Obstetrics"]=9900; //Set up an associative array //The keys represent the filling type //The value represents the cost of the filling i.e. Lemon filling is $5,Dobash filling is $9 //We use this this array when the user selects a filling from the form var society_member= new Array(); society_member["None"]=1; society_member["BCMA"]=0.10; society_member["DCMA"]=0.10; society_member["FOGS"]=0.10; society_member["FNS"]=0.10; society_member["PBCMS"]=0.10; society_member["FSPS"]=0.10; //This function finds the filling price based on the //drop down selection function getPracticeField() { var docPracticeField=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the select id="filling" var selectedPracticeField = theForm.elements["practice"]; //set cakeFilling Price equal to value user chose //For example filling_prices["Lemon".value] would be equal to 5 docPracticeField = practice_field[selectedPracticeField.value]; //finally we return cakeFillingPrice return docPracticeField; } //This function finds the filling price based on the //drop down selection function getSelectedSociety() { var docSelectedSociety=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the select id="filling" var selectedSociety = theForm.elements["society"]; //set cakeFilling Price equal to value user chose //For example filling_prices["Lemon".value] would be equal to 5 docSelectedSociety = society_member[selectedSociety.value]; //finally we return cakeFillingPrice return docSelectedSociety; } //candlesPrice() finds the candles price based on a check box selection function candlesPrice() { var candlePrice=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the checkbox id="includecandles" var includeCandles = theForm.elements["includecandles"]; //If they checked the box set candlePrice to 5 if(includeCandles.checked==true) { candlePrice=5; } //finally we return the candlePrice return candlePrice; } function insciptionPrice() { //This local variable will be used to decide whether or not to charge for the inscription //If the user checked the box this value will be 20 //otherwise it will remain at 0 var inscriptionPrice=0; //Get a refernce to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the checkbox id="includeinscription" var includeInscription = theForm.elements["includeinscription"]; //If they checked the box set inscriptionPrice to 20 if(includeInscription.checked==true){ inscriptionPrice=20; } //finally we return the inscriptionPrice return inscriptionPrice; } function calculateTotal() { //Here we get the total price by calling our function //Each function returns a number so by calling them we add the values they return together var cakePrice = getPracticeField() * getSelectedSociety() + candlesPrice() + insciptionPrice(); //display the result var divobj = document.getElementById('totalPrice'); divobj.style.display='block'; divobj.innerHTML = "Total Price For the Cake $"+cakePrice; } function hideTotal() { var divobj = document.getElementById('totalPrice'); divobj.style.display='none'; } Hello I am fairly new to Javascript. I have a function which takes a string which consists of key value pairs and sets a form control based on key being the form element name and value being the value to set. eg string could be "key1=orange;key2=2;key3=whetever" Here is the function: function processresponse(frm, serverResponse) { var items = serverResponse.split(";"); for(var i = 0; i < items.length; i++) { var item = items[i]; var eqchar = item.search("="); if(eqchar != -1) { var key = item.slice(0, eqchar); var value = item.slice(eqchar+1); var elemname = key; if(document.getElementById(elemname) != null) { var type = frm.elements[elemname].type; if (type=="checkbox") { value == "1" ? frm.elements[elemname].checked=true : frm.elements[elemname].checked=false; } else if (type=="text"){ //do processing for text (text input) frm.elements[elemname].value = value; } else if(type=="select-one"){ //only one is openformmode - default to [0] - true if(value == "0" || value.length == 0) { frm.elements[elemname].options[0].selected = true; } else { frm.elements[elemname].options[1].selected = true; } } else { alert("unknown ctrl type: " + type + " name: " + frm.elements[elemname].name + " val: " + value + " key: " + key); } } //if(frm.getElementById(elemname) } } } The problem line is: var type = frm.elements[elemname].type; elemname is case sensitive so if for example the form element is called dog and the string elemname is Dog, then the line fails with Error: 'elements[...].type' is null or not an object So my check if(document.getElementById(elemname) != null) is insufficient to guard against this. I realise I could do a try catch but there must be a more legant way than that. How can I test the formname more reliably? Any ideas would be very welcome. Angus Hi, firstly I apologise if the title of this thread isn't quite accurate. I'm sure you've all heard it before but I am a complete newbie to Javascript so again: apologies if this is boring and tiresome to even read, let alone help with! I have been asked to make some changes to a form that uses Javascript for the form validation. There is a 'function' that contains the variables of the various form fields and then further code to raise 'alerts' if one of the fields on the form hasn't been filled in. My problem is that for some reason I am unable to add an extra variable to this code after the field of 'County' (this will hopefully make sense when you see the code / link...) and I am stumped as to why. I am able to add variables for all of the other required fields except for 'Postcode' after 'County'. This is the case for both forms. The link is he http://samdelara.co.uk/previews/banq...ation-form.htm and the code I am trying edit is below: function checkAvailibility() { // re-calculate... calculate (); if ( isName() && isAddress1() && isTown() && isCounty() && isPostcode() && isYourEmail() && isFuncDate() && somethingToQuoteFor() && isYourEmailValid() ) { document.ordersummary.emailQuote.value = "No"; setValue(); return true; } else { return false; } } function isName() { if (document.ordersummary.Name.value=="") { alert ("\n Please Enter Your Name") document.ordersummary.Name.focus(); return false; } return true; } function isAddress1() { if (document.ordersummary.Address1.value=="") { alert ("\n Please Enter Your Address") document.ordersummary.Address1.focus(); return false; } return true; } function isTown() { if (document.ordersummary.Town.value=="") { alert ("\n Please Enter Your Town") document.ordersummary.Town.focus(); return false; } return true; } function isCounty() { if (document.ordersummary.County.value=="") { alert ("\n Please Enter Your County") document.ordersummary.County.focus(); return false; } return true; } function isPostcode() { if (document.ordersummary.Postcode.value=="") { alert ("\n Please Enter Your Postcode") document.ordersummary.Postcode.focus(); return false; } return true; } function isYourEmail() { if (document.ordersummary.YourEmail.value=="") { alert ("\n Please Enter Your Email") document.ordersummary.YourEmail.focus(); return false; } return true; } function isFuncDate() { if (document.ordersummary.FuncDate.value=="") { alert ("\n Please Enter Your Function Date") document.ordersummary.FuncDate.focus(); return false; } return true; } function isemailonly() { if (document.ordersummary.emailonly.value=="") { alert ("\n Please Enter Your Email Address") document.ordersummary.emailonly.focus(); return false; } return true; } Any help with this would be very much appreciated and once again, I apologise for my distinct lack of knowledge in this area! Sam I have two password fields on a webpage form. If the passwords don't match, I want to display a message. I could use a popup, I could redirect to a page containing the message with another redirect back to the form or, the option I'd like to use, have a hidden table cell in the form containing the message that displays should the form be submitted without matching passwords. If I use the latter, where do I call the javascript function to display the hidden table cell? So in effect, only javascript function would execute if the passwords don't match, the action page itself shouldn't load at all. Can/should this be done on the action page?
I want to have a button in a form that only calls a Javascript function, but not refresh the page, how do I do this?
Hi all - first post - I'm not too hot on javascript so I don't know if this can be done nor how to search for it in the forum because I don't know what keywords to use - but if I give an idea of what I want to do, perhaps someone can suggest an idea of how to proceed? I have two left floated divs - in the left div I want a series of drop downs (possibly check boxes as well) about a series of products. When the user makes their decision and presses submit, I want the form to submit to a javascript function that says "Right, you will need, from your responses, product C" and in the right hand floated div, a series of hidden product info divs whose visibility is changed depending on which product the function determines is the one for you. Broken down into parts I think I need to do the following: a) Standard HTML form with drop downs etc and submit b) Hidden divs c) Submission process locally to javascript function to determine which product to show/hide d) Javascript function that makes the decision e) Javascript that hides/shows products Unfortunately a server side option is not available; it has to be a client side solution and I only could think of javascript. I can probably handle all bar c) and d) - any pointers, help or suggestions would be great thanks! cheers frank Hi All, I have a button in my html form that will process some functions when user clicks on the button. The problem is after processing the functions, the result is not displayed in the form where I want it to be displayed. I want to ask whether we can create table in the function and display the result in the table row/column but in the same form. Is this possible to be done? And how to do this? In this form cpiM, the input button will call function showIndex. Code: <tr> <td><input type="button" value="Enter" onclick="showIndex(document.cpiM.currFrom.options.selectedIndex, document.cpiM.currTo.options.selectedIndex, document.cpiM.base.options.selectedIndex, document.cpiM.country.options.selectedIndex)"> </td> <td><input type="button" onclick="frmResetM()" value="Reset form" /> </td> </tr> In this function, I want to display the result of calcIndex right below the button Enter in the form cpiM. Code: function showIndex(frm, to, base, country) { for (i=frm; i<=to; i++) { document.write(calcIndex(i, base, country)); document.write("<br/>"); } } I'm still a relative noob and i'm wondering if anyone can help. items use a structured form, so any item in that category will display on the same form when selected i want to have the save button run its normal save on all items except 1 specific item - on the 1 item i want to have it function as a save as copy (while still having "save" as its visible text), the current code set in a drop down list is $options[] = array( 'text' => 'JSAVE', 'task' => $this->getName() . '.save'); $options[] = array( 'text' => 'Save as new project', 'task' => $this->getName() . '.save2copy', 'options' => array('access' => ($this->item->id > 0))); can anyone offer any suggestions? really stuck on this one Hey guys, First shot at JS so please be gentle! I'm trying to get this script to clear the default value of my input elements on focus. It works well the first time, however, if a user inputs some fresh text, selects something else, then selects the same input element again, it will clear the text they entered. Make sense? Here's the script (thanks in advance!!): Code: <script language="JavaScript"> function clickFocus(input){ input.className = 'focus'; if (input.value = input.defaultValue){ input.value = ''; } } function unFocus(input){ input.className = 'entered'; if (input.value == ''){ input.value = input.defaultValue; input.className = 'normal' } } </script> <form action="confirmation.php" method="post" enctype="multipart/form-data" name="form" id="form" onsubmit="return checkForm(this)"> <input type="text" name="name" value="Name" onfocus="clickFocus(this)" onblur="unFocus(this)" /> <input type="text" name="email" value="Email" onfocus="clickFocus(this)" onblur="unFocus(this)" /> <input type="text" name="subject" value="Subject" onfocus="clickFocus(this)" onblur="unFocus(this)" /> <textarea type="text" name="message" onfocus="clickFocus(this)" onblur="unFocus(this)" rows="5">Message</textarea> <input class="submit" name="submit"type="submit" value="Send Message" /> </form> Hi, My webpage can work normally in IE but not in Safari(e.g. when I clicked on some buttons like 'Delete' button, the page opened in Safari stays the same while it should delete the object chosen). When I tried debugging on Safari, after clicking the 'update' button, this message error appeared: "TypeError: Result of expression 'this.form.fireEvent' [undefined] is not a function". I believe this code makes the incompatability between the 2 browser: Code: function DeleteClick() { var frmSWO = document.getElementById("form"); var answer = confirm("Do you really want to delete?") if (answer != 0) { frmSWO.action = "/domsWeb/mtd/doms/web/operation/eDepotMNR/controller/manageWorkOrder/DeleteJobOrImage.do"; frmSWO.method = "post"; this.form.fireEvent('onsubmit'); frmSWO.submit(); } } Any suggest how should I amend the script for it to work on 2 browser concurrently? Thanks all! Hello all, I have a form that submits a POST request when data is submitted. A Servlet then processes this POST request and a JavaBean is used to make some calculations. The HTML response is not generated within the Servlet but instead I forward the request to a JSP to generate the response. - This all works fine, thankfully. However, I am stupidly suck trying to validate the form on the client side with a JavaScript function before the form is submitted. Here is my index.jps: Code: <%-- Document : index Created on : 19-Nov-2009, 13:41:30 Author : lk00043 --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/JavaScript"> <!-- Start hiding JavaScript Statements function validateForm() { var student; var score1, score2, score3, score4; student = document.getElementById('student'); s1 = document.getElementById('score1'); s2 = document.getElementById('score2'); s3 = document.getElementById('score3'); s4 = document.getElementById('score4'); score1 = parseInt(s1.value); score2 = parseInt(s2.value); score3 = parseInt(s3.value); score4 = parseInt(s4.value); if(student.value.length == 0) { document.getElementById('StudentError1').innerHTML = " Enter a student name!"; return false; } if ((isNaN(score1)) || (score1 < 0) || (score1 > 100)) { document.getElementById('Error1').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score2)) || (score2 < 0) || (score2 > 100)) { document.getElementById('Error2').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score3)) || (score3 < 0) || (score3 > 100)) { document.getElementById('Error3').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score4)) || (score4 < 0) || (score4 > 100)) { document.getElementById('Error4').innerHTML = " Enter a number between 0 and 100!"; return false; } } // End hiding JavaScript Statements --> </script> <title>Lab Class 7 - Task 2</title> </head> <body> <h1>Lab Class 7</h1> <form name="collectgrades" action="AssessGrades" method="POST" onSubmit="validateForm()" > Name of Student: <input type="text" name="student" id="student"/><span id="StudentError1"> </span><br /> Presentation: <input type="text" name="score" id="score1"/><span id="Error1"> </span><br /> Writing style: <input type="text" name="score" id="score2"/><span id="Error2"> </span><br /> Technical content: <input type="text" name="score" id="score3"/><span id="Error3"> </span><br /> Depth of analysis: <input type="text" name="score" id="score4"/><span id="Error4"> </span><br /> Feedback:<select name="feedback" size="4" multiple="multiple"> <option>"Could be better structured."</option> <option>"Depth of analysis is good."</option> <option>"Very advanced material."</option> <option>"Very well structured."</option> </select><br /> <input type="submit" value="Submit" /> </form> </body> </html> Regardless of whether incorrect input is given, the data is still POSTed to the server and calculated on or a Server Side error is given. Am I correct in calling the function onClick? The validation essentially needs to be so that: - Student field contains a string - Score1, Score2, Score3 and Score 4 contain a number between 0 and 100 Any help is most appreciated, Cheers, Beetle. Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. |