JavaScript - Changing Onsubmit Form Function To Onchange Form Function
I 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> Similar TutorialsI 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 Hello all, I've been working on a webcode for a basic form and check page. The forms work, just I'm having an issue with when I submit the form, even with incomplete data (AKA the email verification) it submits anyway instead of halting the page. 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>About</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link type="image/x-icon" rel="SHORTCUT ICON" href="EpicIcon.ico" /> <script type="text/javascript"> /* <![CDATA[ */ function firstNameFunc(){ if(document.forms[0].myName.value == 'Enter your first name here.'){ document.forms[0].myName.value = ''; } } function firstNameBlur(){ if(document.forms[0].myName.value == ''){ document.forms[0].myName.value = 'Enter your first name here.'; } } function lastNameFunc(){ if(document.forms[0].myName2.value == 'Enter your last name here.'){ document.forms[0].myName2.value = ''; } } function lastNameBlur(){ if(document.forms[0].myName2.value == ''){ document.forms[0].myName2.value = 'Enter your last name here.'; } } /**E-Mail verification and codes**/ <!--Beginning regular expression function for e-mail check--> <!--End test for Regular Expression--> function emailFocus(){ if(document.forms[0].myEMail.value == 'Enter your email here.'){ document.forms[0].myEMail.value = ''; } } function emailBlur(){ if(document.forms[0].myEMail.value == ''){ document.forms[0].myEMail.value = 'Enter your email here.'; } } <!--Verifying to submitting/resetting the form--> function confirmSubmit(){ var formSubmit = window.confirm("Are you sure you wish to submit the form?"); var emailReg = new RegExp(/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]+\.(com|org|net|edu|gov)$/); /** -- ^[a-zA-Z0-9._-] will check for alpha-numeric characters (upper/lower) as well as allow periods, hyphens, and underscores. -- @ is the combining symbol for email adresses. -- [a-zA-Z0-9.-]+ will allow another set of alpha-numeric numbers that can also contain periods and hyphens. -- \. will seperate the characters from the domain and subdomains. -- (com|org|net|edu|gov)$/ will limit which domains those are. **/ if(document.forms[0].myName.value =='' ||document.forms[0].myName2.value =='' ||document.forms[0].myEMail.value ==''){ alert("You must enter data in the 'First Name,' 'Last Name,' and 'E-Mail' fields."); return false; } else if(document.forms[0].myEMail.value == 'Enter your email here.'){ document.forms[0].myEMail.value = ''; }if(document.forms[0].myEMail.value != ''){ if(emailReg.test(document.forms[0].myEMail.value) == false){ window.alert("Non-certified email used!"); document.forms[0].myEMail.focus(); document.forms[0].myEMail.select(); return true; } return false;} return true; } function confirmReset(){ var formReset = window.confirm("Are you sure you wish to reset the form?"); if(formReset == true) return true; return false; } <!--End of verification--> /* ]]> */ </script> </head> <body> <p align="center"> <form id="userInfo" method="post" onsubmit="confirmSubmit()" onreset="confirmReset()"> <table border="0"> <tr><td> First Name: </td><td align="center"><input type="text" id="myName" value="Enter your first name here." onFocus = "firstNameFunc()" onBlur="firstNameBlur()"/></td></tr> <tr><td>Last Name: </td><td align="center"><input type="text" id="myName2" value="Enter your last name here." onFocus = "lastNameFunc()" onBlur="lastNameBlur()"/></td></tr> <tr><td>E-Mail: </td><td align="center"><input type="text" id="myEMail" value="Enter your email here." onFocus = "emailFocus()" onBlur="emailBlur()"/></td></tr> <tr><td>Message: </td><td align="center"> <textarea id="message" cols="40" rows="5" onFocus="document.forms[0].message.value='';">Enter a message here...</textarea> </td></tr> <tr><td><td align="center"> <input type="Submit" value="Submit"/> <input type="Reset" value="Reset"/> </td></td></tr> </table> </form> </p> <a href="about.html">Click to return</a> </body> </html> Now I've tried making a seperate function for the regular expression and e-mail verification and got no where with it (though I'm sure it can be done easily). My question (though it is bolded): How do I prevent the page from continuing the submit function if data is incomplete? EDIT Code: function confirmSubmit(){ var formSubmit = window.confirm("Are you sure you wish to submit the form?"); var emailReg = new RegExp(/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]+\.(com|org|net|edu|gov)$/); /** -- ^[a-zA-Z0-9._-] will check for alpha-numeric characters (upper/lower) as well as allow periods, hyphens, and underscores. -- @ is the combining symbol for email adresses. -- [a-zA-Z0-9.-]+ will allow another set of alpha-numeric numbers that can also contain periods and hyphens. -- \. will seperate the characters from the domain and subdomains. -- (com|org|net|edu|gov)$/ will limit which domains those are. **/ if(document.forms[0].myName.value =='' ||document.forms[0].myName2.value =='' ||document.forms[0].myEMail.value ==''){ alert("You must enter data in the 'First Name,' 'Last Name,' and 'E-Mail' fields."); return false; } else if(document.forms[0].myEMail.value == 'Enter your email here.'){ document.forms[0].myEMail.value = ''; }if(document.forms[0].myEMail.value != ''){ if(emailReg.test(document.forms[0].myEMail.value) == false){ window.alert("Non-certified email used!"); document.forms[0].myEMail.focus(); document.forms[0].myEMail.select(); return true; } return false;} return true; } How can i change this code to do not duplicate the boxes when one option is selected in the same box as before? http://www.plpgolfandturf.com.au/rr/rrboxes_test.php Code: <script type="text/javascript"> function SetHTML2(type) { //document.getElementById("1").style.display = "none" //document.getElementById("2").style.display = "none" //document.getElementById("3").style.display = "none" //document.getElementById("4").style.display = "none" //document.getElementById("1.1").style.display = "none" //document.getElementById("1.2").style.display = "none" //document.getElementById("1.3").style.display = "none" //document.getElementById("1.4").style.display = "none" document.getElementById("2.1").style.display = "none" document.getElementById("2.2").style.display = "none" document.getElementById("2.3").style.display = "none" document.getElementById("2.4").style.display = "none" document.getElementById("3.1").style.display = "none" document.getElementById("3.2").style.display = "none" document.getElementById("3.3").style.display = "none" document.getElementById("3.4").style.display = "none" document.getElementById("4.1").style.display = "none" document.getElementById("4.2").style.display = "none" document.getElementById("4.3").style.display = "none" document.getElementById("4.4").style.display = "none" document.getElementById("1.1.1").style.display = "none" document.getElementById("1.1.2").style.display = "none" document.getElementById("1.1.3").style.display = "none" document.getElementById("1.1.4").style.display = "none" document.getElementById("1.2.1").style.display = "none" document.getElementById("1.2.2").style.display = "none" document.getElementById("1.2.3").style.display = "none" document.getElementById("1.2.4").style.display = "none" document.getElementById("1.3.1").style.display = "none" document.getElementById("1.3.2").style.display = "none" document.getElementById("1.3.3").style.display = "none" document.getElementById("1.3.4").style.display = "none" document.getElementById("1.4.1").style.display = "none" document.getElementById("1.4.2").style.display = "none" document.getElementById("1.4.3").style.display = "none" document.getElementById("1.4.4").style.display = "none" document.getElementById(type).style.display = "" } </script> <!--Display box --> <font face="Verdana, Geneva, sans-serif" size="4" color="#FF0000"><br /> Search Parts</font><br /> <br /> <select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1">Beck</option> <option value="2">BobCat</option> <option value="3">Briggs</option> <option value="4">Yazoo</option> </select> <span id="1" style="display:none" ><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1.1">Beck 1</option> <option value="1.2">Beck 2</option> <option value="1.3">Beck 3</option> <option value="1.4">Beck 4</option> </select></span> <span id="2" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="2.1">BobCat 1</option> <option value="2.2">BobCat 2</option> <option value="2.3">BobCat 3</option> <option value="2.4">BobCat 4</option> </select></span> <span id="3" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="3.1">Briggs 1</option> <option value="3.2">Briggs 2</option> <option value="3.3">Briggs 3</option> <option value="3.4">Briggs 4</option> </select></span> <span id="4" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="4.1">Yazoo 1</option> <option value="4.2">Yazoo 2</option> <option value="4.3">Yazoo 3</option> <option value="4.4">Yazoo 4</option> </select></span> <span id="1.1" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1.1.1">Beck 1.1</option> <option value="1.1.2">Beck 1.2</option> <option value="1.1.3">Beck 1.3</option> <option value="1.1.4">Beck 1.4</option> </select></span> <span id="1.2" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1.2.1">Beck 2.1</option> <option value="1.2.2">Beck 2.2</option> <option value="1.2.3">Beck 2.3</option> <option value="1.2.4">Beck 2.4</option> </select></span> <span id="1.3" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1.3.1">Beck 3.1</option> <option value="1.3.2">Beck 3.2</option> <option value="1.3.3">Beck 3.3</option> <option value="1.3.4">Beck 3.4</option> </select></span> <span id="1.4" style="display:none"><br /><select onchange="SetHTML2(this.value)"> <option selected="selected">Choose your option</option> <option value="1.4.1">Beck 4.1</option> <option value="1.4.2">Beck 4.2</option> <option value="1.4.3">Beck 4.3</option> <option value="1.4.4">Beck 4.4</option> </select></span> <span id="2.1" style="display:none"> text </span> <span id="2.2" style="display:none"> text </span> <span id="2.3" style="display:none"> text </span> <span id="2.4" style="display:none"> text </span> <span id="3.1" style="display:none"> text </span> <span id="3.2" style="display:none"> text </span> <span id="3.3" style="display:none"> text </span> <span id="3.4" style="display:none"> text </span> <span id="4.1" style="display:none"> text </span> <span id="4.2" style="display:none"> text </span> <span id="4.3" style="display:none"> text </span> <span id="4.4" style="display:none"> text </span> <span id="1.1.1" style="display:none"> text </span> <span id="1.1.2" style="display:none"> text </span> <span id="1.1.3" style="display:none"> text </span> <span id="1.1.4" style="display:none"> text </span> <span id="1.2.1" style="display:none"> text </span> <span id="1.2.2" style="display:none"> text </span> <span id="1.2.3" style="display:none"> text </span> <span id="1.2.4" style="display:none"> text </span> <span id="1.3.1" style="display:none"> text </span> <span id="1.3.2" style="display:none"> text </span> <span id="1.3.3" style="display:none"> text </span> <span id="1.3.4" style="display:none"> text </span> <span id="1.4.1" style="display:none"> text </span> <span id="1.4.2" style="display:none"> text </span> <span id="1.4.3" style="display:none"> text </span> <span id="1.4.4" style="display:none"> text </span> <br /> <br /><a href="http://www.plpgolfandturf.com.au/rr/rrboxes_test.php"><img src="http://www.plpgolfandturf.com.au/rr/bt2.png" border="0" /></a> Hi all, I'm new to javascript and am having a few issues. I have a function that I want to run with multiple onchange events. My page has several image selection buttons and I want it to preview the image when/if each one is selected. I have gotten it working for the first on the page but cannot for the remainder. Is this possible or am I wishful thinking? Foster Reply With Quote 01-17-2015, 10:23 AM #2 Arbitrator View Profile View Forum Posts Senior Coder Join Date Mar 2006 Location Splendora, Texas, United States of America Posts 3,423 Thanks 32 Thanked 293 Times in 287 Posts Originally Posted by Foster I'm new to javascript and am having a few issues. I have a function that I want to run with multiple onchange events. My page has several image selection buttons and I want it to preview the image when/if each one is selected. I have gotten it working for the first on the page but cannot for the remainder. Is this possible or am I wishful thinking? Where's the code? If you simply want to assign multiple listeners for the same event on a single element, use element.addEventListener("change", eventHandler) instead of element.onchange = eventHandler or <element onchange="eventHandler();"></element>. I probably have gone about this all wrong since I am a complete noobe, but if someone could point me in the right direction I would be very thankful. Here is the situation. What works: I have a drop menu that is being generated by a PHP/MYSQL script, when you choose an option the onchange event is triggered and runs a function that sends the value to a php script so a graphical image can be generated and saved with a random file name. The randomly generated image name is sent back as an XML response and then image is displayed with src The Problem: I need to be able to have a function store the value from the onchange event and run again when the page refreshes. As of right now, when the page refreshes the image is gone. I have attempted to do this with cookies, but not exactly sure how I will do this and I have finally decided to ask for help. I hope my explanation is not confusing, please let me know if you need more info or if you need to see my code. Hi there, I have a drop down menu that runs a function when one of the options are chosen. Is there a way to have this run from individual links? <select name="users" onChange="showUser(this.value)"> <option value="">Select a Deer:</option> <option value="1">8002</option> <option value="2">8009</option> <option value="3">8011</option> Thanks Rich Hey all, I have a little function that performs when a form item is selected. I would like to give the form items all at once and have the function perform when the user mouses over an item in the displayed list. Here is the form code: Code: <form> <select onchange="showRSS(this.value)"> <option value="">Select an RSS-feed:</option> <option value="Google">Google News</option> <option value="MSNBC">MSNBC News</option> </select> </form> thanks a bunch, Brian p.s. I tried this but it didn't work Code: <?php echo("<a href=\"http://www.msn.com\" onMouseover=\"showRSS(this.MSNBC)\">MSNBC News</a>");?> <br /> <?php echo("<a href=\"http://www.google.com\" onMouseover=\"showRSS(this.Google)\">Google News</a>");?> <br /> 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? I'm a newbie to scripting who needs help. The situation is as follows: I'm running Joomla 1.5.23 and I've been trying to get validation on a component's form fields. In the header section, I'm properly loading the validator.js file, which contains the following: Code: //function to check empty fields function isEmpty(strfield1, strfield2) { strfield1 = document.forms[0].firstname.value strfield2 = document.forms[0].lastname.value //firstname field if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') { alert("\"firstname\" is a mandatory field.\nPlease amend and retry.") return false; } //lastname field if (strfield2 == "" || strfield2 == null || strfield2.charAt(0) == ' ') { alert("\"lastname" is a mandatory field.\nPlease amend and retry.") return false; } } return true; } //function to check valid email address function isValidEmail(strEmail){ validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i; strEmail = document.forms[0].email.value; // search email text for regular exp matches if (strEmail.search(validRegExp) == -1) { alert('A valid e-mail address is required.\nPlease amend and retry'); return false; } return true; } //function that performs all functions, defined in the onsubmit event handler function check(form)){ if (isEmpty(form.firstname)){ if (isEmpty(form.lastname)){ if (isValidEmail(form.email)){ return true; } } } return false; } I'm invoking this in this way: Code: <form action="index.php?option=com_pbbooking&task=save" method="POST" onsubmit="return check(this);"> My problem is that even if all fields are empty it will go to the next step. Thanks in advance, twdk01. I want have an alert pop up if the email is invalid and have the form not post. I have tried countless ways but cannot figure it out. No matter what I do, it always posts. Thanks in advance for the help. Code: <html> <head> <script language = "Javascript"> function echeck(str) { var at = "@" var dot = "." var lat = str.indexOf(at) var lstr = str.length var ldot = str.indexOf(dot) if(str.indexOf(at) == -1) { alert("Invalid E-mail ID") return false } if(str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) { alert("Invalid E-mail ID") return false } if(str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) { alert("Invalid E-mail ID") return false } if(str.indexOf(at, (lat + 1)) != -1) { alert("Invalid E-mail ID") return false } if(str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) { alert("Invalid E-mail ID") return false } if(str.indexOf(dot, (lat + 2)) == -1) { alert("Invalid E-mail ID") return false } if(str.indexOf(" ") != -1) { alert("Invalid E-mail ID") return false } return true } function ValidateForm() { Var emailID = document.frmSample.txtEmail if((emailID.value == null) || (emailID.value == "")) { alert("Please Enter your Email ID") emailID.focus() return false } if(echeck(emailID.value) == false) { emailID.value = "" emailID.focus() return false } return true } </script> <form name = "frmSample" action = "https://www.pipelinedeals.com/web_lead" onsubmit = "return validateForm();" method = "post"> <input type = "hidden" name = "w2lid" value = "removed for privacy" /> <input type = "hidden" name = "thank_you_page" value = "http://www.fatsfixedassettracking.com/thanks.html"/> <p>Enter email address: <input type = "text" name = "txtEmail"> </p> <p><input type = "submit" name = "Submit" value = "Submit"></p> </form> </head> </html> 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> If my php variable, (which is retrieved from a mysql table in the php code, not shown) is equal to "1", that means the member is not eligible to submit the form, so I want an alert() to say "member not eligible!". Else, I want it to continue to submit the form. Here is my code (which I can't seem to get to work): <head> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> function ismaxlength(obj){ var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "" if (obj.getAttribute && obj.value.length>mlength) obj.value=obj.value.substring(0,mlength) } //this first script is for something else, to check the max length of characters in a text area </script> //here is the script in question <script type="text/javascript"> <!-- var mem_eligible = "<?= $is_mem_eligible ?>"; if (mem_eligible == "1") { function MoveOn() { alert('You are not yet eligible, please try again tomorrow!'); } } --> </script> </head> <form name="myform" action="postform.php" method="post" enctype="multipart/form-data"> <div> <input type="submit" name="Submit2" value="Submit Entries" onclick="MoveOn()"/> </div> </form> Please help, thanks! June 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'; } I am wondering if it is possible for me to replace my form submit button with an animated gif (fake progress bar), after the button has been pressed. Having so far disabled the button onclick, I would instead be happy if I could simply change the button text from 'Click here to submit' to 'Processing...' I have done some searches here but I'm finding references to innerHTML, etc., and I'm getting lost now. Is this an easy thing to do? TIA I've got this listbox full of hundreds of employee names. Clicking on a name executes a function using onchange. Because of the length of the list I decided a search function would be really handy and I finally found one that works. Now the search function, when you type in the input box, scrolls the list to the first matching entry. And that's good, that's what I wanted. The problem comes in when you try to click on the name the search function found. Nothing happens ofcourse because the onchange tag in the list reacts to changes, not direct clicks. <select onchange="display.apply(this, this.value.split(','))" multiple="multiple" id="People" name="People" style="border-style: none; height:260px; width:220px; margin-bottom: 15px;"> <option selected="selected">Loading</option> </select> The list is populated by java but for testing I disabled the function that clears the "Loading" option and I set it to selected. That way the loading option is highlighted by default and the search function is free to highlight something else, then when I click on the search result it works like it's supposed to. But keeping a highlighted option at the top of the list for that sole purpose isn't very elegant, especially since if you click on it the onchange function tries to execute and generates errors. The only solution I can think of is to use java to generate another option way at the bottom of the list that has the selected attribute but I don't quite know how to do that. Does anyone have any thoughts on what I can do? 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 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?
|