JavaScript - How To Prevent Form Submission Unless Certain Criteria Are Met??
Hello. I have what I think is a simple request, but I'm not quite sure how to go about it. I hope you can help me!
Problem: I am building an online store and need to restrict checkout unless a customer has bought at least $20 worth of items. If they have >$20, they can check out. If they have <$20, they should get an error when they click the checkout button that explains that there is a $20 minimum. I don't want them to be able to checkout, so maybe I also need to disable the button or hide it? Here are the two elements in my HTML: The total price div: Code: <div id="totalprice">{tag_productgrandtotal}</div> The checkout button: Code: {tag_buybutton,<img alt="" src="/CatalystImages/shop_checkout.png" />} Here is what I've tried to put together with my bare minimum knowledge of Javascript: Code: <body onload="checkOut()"> <script type="text/javascript"> function checkOut() { var tp = document.getElementById('totalprice').innerHTML; tp = tp.replace(/[^0-9$\.]/g,""); // strip anything except numbers decimals and $ sign if (tp < "$20.00") { ???????????????? } else { ????????????????? } } </script> I'm not sure the top part is correct, and where I've put "?????" I have no idea what to do to deactivate the checkout button and produce the error message. Thank you SO much for any help you can provide. Similar TutorialsHi there, I'm very very new to programming and I think what I'm after is possible but I'm not 100% sure. Here it goes: I've got a search form in my website that is corresponds to a external searchable database - Caspio. The site is Wordpress and the search form is deployed via a url wrapped inside the Caspio plugin shortcode. I'd like to create some javascript to pre-select elements in the search form. I want to be able to do this externally from Caspio because I want to set up 20-30 of these pre-sorted searches. This will make it easier for clients to access the most popular searches. I've tried to research how to do this but I haven't been able to find very much - perhaps I'm using the wrong words. Any help would be much appreciated! Many thanks I have been hard at work coding a fancy JQuery form validation script. Problem is, when I run validation on my form, it seems to work, but no email is sent. But when I disable validation, the email sends just fine. I am fairly new to JavaScript, and need some help pinpointing where my error is. Here is the code. Code: // BEGIN JAVASCRIPT $(function(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'your email', 'yourmessage' : 'I would like to inquire about' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('textarea#yourmessage').inputfocus({ value: field_values['yourmessage'] }); //form validation $('form').submit(function validateForm(){ return false }); // removing this return false seems to mess up validation $('#submit').click(function(){ //remove classes $('#sendamessage input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#sendamessage input[type=text],#sendamessage textarea'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<2 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); // css class $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); // css class } }); if(!error) { // this is where I get confused. How do I make this send the form? alert('Data sent'); }); } }); }); // END JAVASCRIPT <form method="post" action="" onsubmit="return validateForm()" > <input type="hidden" name="ccf_customhtml" value="1" /> <input type="hidden" name="success_message" value="Thank you for filling out our form!" /> <input type="hidden" name="destination_email" value="dauidus@gmail.com" /> <input type="hidden" name="required_fields" value="" /> <label for="name">Name</label> <input type="text" name="name" id="name" value="your name" /> <label for="email">Email</label> <input type="text" name="email" id="email" value="your email" /> <label for="yourmessage">Your Message</label> <textarea name="yourmessage" id="yourmessage" value="I would like to inquire about" style="margin-bottom:20px;" />I would like to inquire about</textarea> <input class="send submit" id="submit" type="submit" value="" style="position: relative; bottom: -70px; left: 25px; " /> </form> I am using a WordPress plugin to automatically send the contents of the form to email. It works without the javascript enabled. But when I turn on JS the form gets validated, but no email is sent. Please let me know if I should include anything else here... I've been looking at this code so much that I'm having a hard time doing it with fresh eyes. The problem page is on http://new.dauidusdesign.com/contact/. FYI, I am also looking to make this work with the 'request a quote' link on the same page. Cheers! -Dave Hi. I am new here. I wanted help for a JavaScript code. You might think I'm lazy for not writing it myself, but the truth is I am not a JavaScript coder. I just have a really simple website and I am trying to do something for which I know JS is required but I don't know how to do it. I've also searched around but couldn't find the appropriate code. I created a submission form for users when they log in to my website they can submit their info . when they fill the form and click on submit button is not sending the info to my email .............................please help here is my my codes please take a look at it Thanks 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"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="verify-v1" content="N1J6LLa/OdGf52xzkbegP/YFAD+RaeKa9FQ2/8UJfKo="> <title>southernfiremag.co.za</title> <link href="southernfiremag.co.za_files/webstyle.css" rel="stylesheet" type="text/css"> <link href="southernfiremag.co.za_files/balloontip.css" rel="stylesheet" type="text/css"> <script src="southernfiremag.co.za_files/balloontip.js" type="text/javascript"></script><style media="screen" type="text/css">#FLheader {visibility:hidden}</style><style media="screen" type="text/css">#subFlash {visibility:hidden}</style><style media="screen" type="text/css"> #footer {visibility:hidden}.style1 {color: #FFFFFF} body { background-color: #000000; } </style></head><body class="sIFR-active"><div id="dhtmltooltip"></div> <script src="southernfiremag.co.za_files/gen_validatorv2.js" type="text/javascript"></script> <div id="container"> <script type="text/javascript"> var flashvars = { dater:'', }; var params = {}; params.menu = "false"; params.wmode = "transparent"; params.bgcolor = "#1A1A1A"; var attributes = {}; swfobject.embedSWF("/header.swf", "FLheader", "977", "145", "8.0.0", false, flashvars, params, attributes); </script> <div id="maincontent"> <script type="text/javascript"> var flashvars = { }; var params = {}; params.menu = "false"; params.wmode = "transparent"; params.bgcolor = "#1A1A1A"; var attributes = {}; swfobject.embedSWF("/subHeader.swf", "subFlash", "963", "167", "8.0.0", false, flashvars, params, attributes); </script> <div class="textArea"> <div id="crumbsBar"><b><a href="http://www.southernfiremag.co.za/">SOUTHERN FIRE MAG</a></b> >> <a href="http://www.southernfiremag.co.za/submissions/model_submission.php">MODEL SUBMISSION </a> >> Submit to modelsubmission@southernfiremag.co.za</div> <div id="adPanel"> <img src="southernfiremag.co.za_files/become_Southern Fire Girl.png" border="0" height="258" width="292"><br> <!-- <a href="/join/"><img src="/images/membershipPrice.jpg" alt="" width="186" height="117" border="0" /></a><br />--> <img src="southernfiremag.co.za_files/index_20.jpg" alt="" height="258" width="292"><br> <img src="southernfiremag.co.za_files/ban_secure.jpg" alt="" height="120" width="186"><br> <img src="southernfiremag.co.za_files/ban_updates.jpg" alt="" height="120" width="186"><br> <br> <br class="clear"> </div> <div id="mainPanel"> <h1 style="" class="sIFR-replaced"> </h1> <h2 class="sIFR-replaced" style="width: 460px;"> </h2> </div> <br class="clearLeft"> <div style="width: 400px; float: left;"> <p><span class="style1">Fill out this form with your pics. Be sure to include head-shots, commercial fashion, glamour/swim and beauty. </span></p> <div> <form action="index.htm" method="post" enctype="multipart/form-data" name="SOUTHERN FIRE MAG" id="SOUTHERN FIRE MAG"> <table class="tableBK" border="0" cellpadding="3" cellspacing="1" width="400px"> <!--DWLayoutTable--> <tbody><tr> <td colspan="2" height="35"></td> </tr> <tr> <td width="141" height="24"><b class="formfont"><span style="color: red">*</span><span class="style1"> Name: </span></b></td> <td width="242"><input name="name" id="name" size="25" type="text"> </td> </tr> <tr> <td height="24"><b><span style="color: red">*</span><span class="style1"> Email:</span></b></td> <td><input name="email" id="email" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Address:</span></td> <td><input name="address" id="address" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">City:</span></td> <td><input name="city" id="city" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">State:</span></td> <td><input name="state" id="state" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Zip:</span></td> <td><input name="zip" id="zip" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Phone:</span></td> <td><input name="phone" id="phone" size="25" type="text"> </td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="24"><span style="color: red">*</span><span class="style1"> Stage Name:</span></td> <td><input name="alias" id="alias" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Age:</span></td> <td class="tdGrey2"><input name="age" id="age" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Ethnicity:</span></td> <td class="tdGrey2"><input name="ethnicity" id="ethnicity" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Height:</span></td> <td class="tdGrey2"><input name="height" id="height" size="25" type="text"></td> </tr> <tr> <td height="25"><span class="style1">Weight:</span></td> <td class="tdGrey2"><select name="weight"> <option selected="selected" value="85-99">85-99</option> <option value="100-110">100-110</option> <option value="111-115">111-115</option> <option value="116-125">116-125</option> <option value="126-135">126-135</option> <option value="136-145">136-145</option> <option value="146-155">146-155</option> <option value="156-165">156-165</option> <option value="Other">Other</option> </select></td> </tr> <tr> <td height="24"><span class="style1">Bust:</span></td> <td class="tdGrey2"><input name="bust" id="bust" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Waist:</span></td> <td class="tdGrey2"><input name="waist" id="waist" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Hip:</span></td> <td class="tdGrey2"><input name="hip" id="hip" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Shoe:</span></td> <td class="tdGrey2"><input name="shoe" id="shoe" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Dress:</span></td> <td class="tdGrey2"><input name="dress" id="dress" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Agency:</span></td> <td class="tdGrey2"><input name="agency" id="agency" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Personal Website:</span></td> <td class="tdGrey2"><input name="website" id="website" size="25" type="text"></td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="45" colspan="2"><span class="style1">We have several different photographers that we work with in the following Country. Please select which Country you are willing to meet with our photographers if selected for a test shoot? </span></td> </tr> <tr> <td height="25"><span class="style1">Country:</span></td> <td><!--<input name="location" type="text" id="location" size="25" value="" > --> <select name="location"> <option selected="selected" value="SOUTH AFRCA">SOUTH AFRICA</option> <option value="USA">USA</option> <option value="DRC CONGO">DRC CONGO</option> <option value="ANGOLA">ANGOLA</option> <option value="MOZABIQUE">MOZABIQUE</option> <option value="MILAN">MILAN</option> <option value="OTHERS">OTHERS</option> </select></td> </tr> <tr> <td colspan="2" height="2"></td> </tr> <tr> <td height="32" colspan="2"><span style="color: red;">Image upload is required.</span> <span class="style1">Please upload 1 or up to 4 images below. Each image size must be below 1MB</span></td> </tr> <tr> <td colspan="2" height="2"></td> </tr> <tr> <td height="27"><span style="color: red">*</span><span class="style1"> Image 1</span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label> </td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 2 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 3 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 4 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="24"><span class="style1">Myspace<b>:</b></span></td> <td><input name="myspace" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">ModelMayhem<b>:</b></span></td> <td><input name="mayhem" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Facebook<b>:</b></span></td> <td><input name="facebook" size="25" type="text"></td> </tr> <tr> <td height="8" colspan="2"> <hr> </td> </tr> <tr> <td height="24"><span class="style1">Twitter<b>:</b></span></td> <td><input name="twitter" size="25" type="text"></td> </tr> <tr> <td height="32" colspan="2"> <span class="style1">Have a twitter account? If so, let us know your account and we'll post your tweets here. </span></td> </tr> <tr> <td height="8"></td> <td></td> </tr> <tr> <td height="87" valign="top"><span class="style1">TV</span></td> <td> <textarea name="tv" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Film</span></td> <td> <textarea name="film" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Commercial</span></td> <td> <textarea name="commercial" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Advertising</span></td> <td> <textarea name="advertising" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Editorial</span></td> <td> <textarea name="editorial" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Music Video</span></td> <td> <textarea name="music" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Web</span></td> <td> <textarea name="web" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="26" valign="top"><span class="style1">Tattoos?</span></td> <td> <input name="tyn" value="yes" type="radio"> Yes <input name="tyn" value="no" checked="checked" type="radio"> No<br> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Give more details about your tattoos...</span></td> <td> <textarea name="tattoos" cols="45" rows="6" id="tattoos"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Why are you the right girl for SOUTHERN FIRE...</span></td> <td><textarea name="description" cols="45" rows="6" id="description"></textarea> </td> </tr> <tr> <td height="24" valign="top"><span class="style1">3 + 4 =?</span></td> <td> <!-- <img src="/submissions/random_code/code.php" alt="" /><br /> --> <input name="code" type="text"> </td> </tr> <tr> <td colspan="2" class="tablebar" height="2"></td> </tr> <tr> <td height="41" colspan="2" align="center" class="tdGrey2"> <input name="action" id="action" value="sendform" type="hidden"> <input name="Submit" src="southernfiremag.co.za_files/confrim.gif" value="SUBMIT" type="image"> </td> </tr> <tr> <td colspan="2" class="tdGrey" height="5"></td> </tr> </tbody></table> </form> <script language="JavaScript" type="text/javascript">//You should create the validator only after the definition of the HTML form var frmvalidator = new Validator("SOUTHERN FIRE MAG"); frmvalidator.addValidation("email","maxlen=50"); frmvalidator.addValidation("email","req","Please enter your email address"); frmvalidator.addValidation("email","email"); frmvalidator.addValidation("name","req","Please enter your name"); frmvalidator.addValidation("alias","req","Please enter your alias"); </script> </div> </div> <div style="width: 250px; float: left; text-align: left; margin-left: 10px;"> <!-- right side - inner content --> <!-- <img src="/images/extra/041410/bmd1.jpg" alt="" /><br /><br /> <img src="/images/extra/041410/bmd2.jpg" alt="" /><br /><br /> <img src="/images/extra/041410/bmd3.jpg" alt="" /><br /> --> </div> <br class="clear"> </div> <br class="clear"> </div> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script><script src="southernfiremag.co.za_files/ga.js" type="text/javascript"></script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-589703-16"); pageTracker._trackPageview(); } catch(err) {} </script> </body></html> I have the below code to validate and send my form. It sends the email fine, but I receive the error message at the bottom of the page instead of the success message. Any help on why it is doing this would be great. This is my first form validation script. Here is the page live: Website here is the javascript: Code: $(document).ready(function() { $('form #response').hide(); $('#submitbtn').click(function(e) { e.preventDefault(); var valid = ''; var required = ' is required.'; var name = $('form #name').val(); var phone = $('form #phone').val(); var email = $('form #email').val(); var details = $('form #details').val(); var honeypot = $('form #honeypot').val(); var humancheck = $('form #humancheck').val(); if (!name.match(/^[A-Za-z ]{3,20}$/)) { valid = '<p>- Your name' + required +'</p>'; } if (!phone.match(/^([1]-)?[0-9]{3}-?[0-9]{3}-?[0-9]{4}$/i)) { valid += '<p>- A valid phone number' + required +'</p>'; } if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) { valid += '<p>- A valid email address' + required +'</p>'; } if (honeypot != 'http://') { valid += '<p>Spambots are not allowed.</p>'; } if (humancheck != '') { valid += '<p>A human user' + required + '</p>'; } if (valid != '') { $('form #response').removeClass().addClass('error') .html('<strong>Please correct the errors below:</strong>' + valid).fadeIn('fast'); } else { $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast'); var formData = $('form').serialize(); submitForm(formData); } }); }); function submitForm(formData) { $.ajax({ type: 'POST', url: 'bookings.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<strong>There was an error. Please use the above information and contact us directly.</strong>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; PHP Code: PHP Code: <?php sleep(4); $name = trim(stripslashes(htmlspecialchars($_POST['name']))); $phone = trim(stripslashes(htmlspecialchars($_POST['phone']))); $email = trim(stripslashes(htmlspecialchars($_POST['email']))); $details = trim(stripslashes(htmlspecialchars($_POST['details']))); $humancheck = $_POST['humancheck']; $honeypot = $_POST['honeypot']; if ($honeypot == 'http://' && empty($humancheck)) { //Validate data and return success or error message $error_message = ''; $name_check_exp = "/^[A-Za-z ]{3,20}$/"; $phone_check_exp = "/^([1]-)?[0-9]{3}-?[0-9]{3}-?[0-9]{4}$/i"; $email_check_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/"; if (!preg_match($name_check_exp, $name)) { $error_message .= "<p>Your name is required.</p>"; } if (!preg_match($phone_check_exp, $phone)) { $error_message .= "<p>A valid phone number is required.</p>"; } if (!preg_match($email_check_exp, $email)) { $error_message .= "<p>A valid email address is required.</p>"; } if (!empty($error_message)) { $return['error'] = true; $return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message; echo json_encode($return); exit(); } else { //send to an email $emailSubject = 'Bookings Form'; $webMaster = 'some.email@gmail.com'; $body=" <br><hr><br> Name: $name <br> Phone: $phone <br> Email: $email <br> Details: $details "; $headers = "From: $email\r\n"; $headers .= "Content-type: text/html\r\n"; //send email and return to user if(mail($webMaster, $emailSubject, $body, $headers)) { $return['error'] = false; $return['msg'] = "<p>Message sent successfully. Thank you for your intrest " .$name .".</p>"; echo json_encode($return); } else { $return['error'] = true; $return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>"; echo json_encode($return); } } } ?> Ok, I am reasonably new to javascript, and I have been trying to code some really basic client-side form validation. The validation part is working, but for some reason the form won't submit if no errors are found. I have tried all different variations of the submit syntax. i.e. document.login_form.submit();. But settled with the one on W3Schools even though it still didn't work. I would really appreciate any advise. Here is my code: Code: <head> <title>Project Rival - Authentication</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function verify() { var themessage = "Please enter your"; if (document.login_form.user.value=="") { themessage = themessage + " username"; } if (document.login_form.user.value=="" && document.login_form.pass.value=="") { themessage = themessage + " and"; } if (document.login_form.pass.value=="") { themessage = themessage + " password"; } //alert if fields are empty and cancel form submit if (document.login_form.user.value!="" && document.login_form.pass.value!="") { document.getElementById("login_form").submit(); return true; } else { document.getElementById("error").innerHTML = themessage; return false; } } </script> </head> <body> <div id="container"> <div id="login_box_top"> </div> <div id="logo"><img src="images/projectrival.jpg" width="150"/></div> <div id="error"></div> <div id="login"> <form action="login.php" method="post" name="login_form" id="login_form"> <input name="user" class="input" id="user" type="text" size="30" maxlength="30" /><br /><br /> <input name="pass" class="input" id="pass" type="password" size="30" maxlength="30" /><br /><br /> <input name="submit" id="submit" type="button" value="Login" onclick="verify()" /> </form> </div> <div id="login_box_bottom"> </div> <div id="copy"><p>© Martin Day 2011 </div> </div> </body> </html> Many Thanks Hi I have an insert form.....to insrt data to DB. if user typed in something, BUT clicked on an url in navigation menu TO GO to an OTHER Page...I would be able to give an alert to user-"please submit the form" some thing that way.....Is it possible to do?? pls suggest me some example... TIA I have this form he When a user enters a value in the quantity field that is NaN then a alert messages comes up for the user, also when the NAN is entered the value is submitted on the form. If the user enters a number then then that number is submitted on the form. What I want to do is when the user enters NAN the alert keeps coming up and the value is not submitted on the form, but if they enter no value or a number those values will be submitted on the form. Code: <script> function getCost(tool,price){ var tags = document.getElementsByName(tool); var str = tags[0].value; str = str.trim(); if (str == "") return 0; var quanity = Number(str); if(isNaN(quanity)) { alert("Please enter a valid number for the " + tool); quanity = 0; return false; } } function validateInput(){ val = getCost("Saw",12); if (val == "NaN") return false; val = getCost("Hoe",18); if (val == "NaN") return false; val = getCost("Tree Trimmer",22); if (val == "NaN") return false; } </script> <form action="http://crm.abc.com/formtest.php" method="post" onsubmit="return validateInput();"> <p> <label> Buyer's Name: <input type="text" name="name" size="30"/> </label> <label> Street Address: <input type="text" name="street" size="30"/> </label> <label> City, State, Zip: <input type="text" name="city" Size="30"/> </label> </p> <table> <tr> <th> Tool Name </th> <th> Price </th> <th> Quantiy </th> </tr> <tr> <td> Saw </td> <td> $12.00</td> <td> <input type= "text" name="Saw" size="2" /> </td> </tr> <tr> <td> Hoe </td> <td> $18.00 </td> <td> <input type="text" name="Hoe" size="2" /> </td> </tr> <tr> <td> Tree Trimmer </td> <td> $22.00 </td> <td> <input type="text" name="Tree Trimmer" size="2" /> </td> </tr> </table> <h2> Payment Method </h2> <label> Visa <input type="radio" name="payment" id="payment_visa" value="visa" checked="checked"/> </label> <br /> <label> Mastercard <input type="radio" name="payment" id="payment_mastercard" value="mastercard"/> </label> <br /> <label> American Express <input type="radio" name="payment" id="payment_american_express" value="american express"/> </label> <br /> <input type="submit" value="Submit" /> </form> Hello, I'm using simple form validation, found online, to check certain fields before submitting. The problem is that, although the script detects the error/missing field/wrong syntax and pops up the corresponding alert, after the user presses OK in the alert box the script continues and sends the form - which of course is not valid. HTML PART: Code: <input name="Submit" type="submit" class="textfield" value="Register" onclick="checkitems();"> JAVASCRIPT PART: Code: function checkitems() { valid = true; if ( document.registration.Onoma.value == "" ) { alert ( "Please enter your name." ); return false; } if ( document.registration.HlekDieuthinsi.value == "" ) { alert ( "Please enter your email." ); return false; } var e=document.registration.HlekDieuthinsi.value var emailFilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i if (!(emailFilter.test(e))) { alert ( "The email address you entered is not valid." ); return false; } return valid; } I am trying to submit my form and receive a success message that go's away. My form validation is working fine and I receive the email, but the echo back to json is giving my error message instead of my success message. This is my first try doing this and am brand new to javascript. If anyone could please help me figure out what is wrong or tell me how to rewrite it, I would be much obliged. Code: function submitForm(formData) { $.ajax({ type: 'POST', url: 'bookings.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<strong>There was an error. Please use the above information and contact us directly.</strong>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; All my parameters will not work after my first form submission unless I refresh my page. Is there a way to refresh the page after the page loads without a continuous loop of refreshes?
Hi and hope someone can help. I have a form with various input fields and, on submission, I'd like some validation done and if that's OK, for it to load another page in the parent directory. Trouble is I end up with Error 404 when I test it, the page actually exists but when I look at the URL within the Error 404 page it looks like this... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/pages/register()?First_Name=&Initials=&Last_Name=&Address_Line_1=&Address_Line_2=&City=&County=&Post_Code=&Email=&submit=Register The URL with the form on it is... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/pages/wm6ex1_register.html and the page I'm trying to call is... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/wm6ex1_home.html Is the problem to do with the fact that the form is actually trying to pass all those variables from the input fields? My form looks like this... Code: <form method="get" name="register" action="register()" onreset="return confirm('This will remove all your entries so far.\nIs that O.K?')" > Various input fields here. <input type="reset" name="reset" value="Reset" /> <input type="submit" name="submit" value="Register" /> </form> My function currently has no validation and simply looks like this... Code: function register() { window.open("../wm6ex1_home.html", "_self") } My thanks R For part of a project, I'm trying to create an order form with a real-time calculator (so, for example, if you enter in a quantity of a product into a form input box, it will multiply that quantity with the price of the product and display the total price in a different form input box). Most of the code works, in the sense that when I press the submit button on the form, I can see all of the values of each of the form input boxes in the address bar. However, when I wrote a function that sums all of the individual total prices into a final price and displays that in another form input box, pressing the submit button no longer puts the value of each field into the address bar. (In effect, everything works if I remove this code...but I really want to include it, since it seems like such a logical part of my intentions with this webpage.) Here's the function that I'm trying to get to work with the form. ("orderform" is the name of the form, and all of the "t#"s are the individual total prices that I'm trying to sum.) I know this code is probably far from the most efficient solution, but as long as it works...ahaha... Code: function totaled(){ b = parseInt(document.orderform["t0"].value); c = parseInt(document.orderform["t1"].value); d = parseInt(document.orderform["t2"].value); e = parseInt(document.orderform["t3"].value); f = parseInt(document.orderform["t4"].value); g = parseInt(document.orderform["t5"].value); h = parseInt(document.orderform["t6"].value); i = parseInt(document.orderform["t7"].value); j = parseInt(document.orderform["t8"].value); a = b+c+d+e+f+g+h+i+j; document.orderform["total"].value = a; } Could anyone help me out, in explaining why my code is messing up the form submission? And I really really apologize if anyone out there is appalled by some ignorance of mine - I'm only just starting to learn how to use JavaScript. (Also, I'm sorry if I referred to things with the wrong terms and confused anyone. I'm not too good with proper naming either.) Oh, right! Just wanted to add, the code does exactly what it's supposed to do (minus the messed up form submission) and nothing comes up in the Error Console when I open my webpage, so there's no help to be found there. (I doubt that was actually helpful, but just in case...) Hello there, I hope you might be able to help me with an issue I'm having getting a form to validate before submission. I've been trying to figure out where I'm going wrong but being relatively new to javascript I'm obviously missing something. I have a form which calls one of two validation scripts with onBlur for each field (I've only included one of each field, there are 8 fields in total in the form): Code: <form name="submitrunnertime" action="http://......reflect.php" onsubmit="return valResultsForm();" method="post"> <table> <tr><td><label for="RunnerID">Runner ID</label></td> <td><input type="text" name="RunnerID" size="5" maxlength="5" onBlur="valRange(RunnerID, 1, 99999, 'RunnerID_bk');" /> </td><td id="RunnerID_bk"><span></span></td></tr> <tr><td><label for="">Date (YYYY-MM-DD)</label></td> <td><input type="text" name="Date" size="10" maxlength="10" onBlur="valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format');" /> </td><td id="Date_bk"><span></span></td></tr> etc. etc. </table> <input type="submit" name="submitrunnertime" value="submit"> </form> I've managed to get each individual field to validate as the form is filled in. Now, if I fill valResultsForm.js with a simple line return false; then the form refuses to submit as it should do, but if I try and re-run the validation of each field so that the form will only submit if all fields have been filled in correctly, even if I force valResultsForm to return a false result, the form still submits. I just can't figure out why it is doing this and it's driving me around the bend. valResultsForm looks like: Code: function valResultsForm() { var res1 = valRange(RunnerID, 1, 99999, 'RunnerID_bk'); var res2 = valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format'); if (res1 == true && res2 == true) { return true; } else { return false; } } Any hints or advice that anyone could give me would be hugely appreciated. Thank you, Andrew I have rough ideas on how to achieve this but I dont know how to start. I want to use a drop-down menu selection option to submit a form. But the form's contents change depending on the option. This is the basic form: Code: <FORM ID="go1" METHOD="POST" TARGET="_self"> <INPUT TYPE=HIDDEN NAME=UserID VALUE="<%UserID%>"> <INPUT TYPE=HIDDEN NAME=Password VALUE="<%Password%>"> <INPUT TYPE=HIDDEN NAME=SubUnitID VALUE="4266"> <INPUT TYPE=HIDDEN NAME=PageID VALUE="1"> <INPUT TYPE="IMAGE" class="hand" border="0" src="/images/my.gif" width="45" height="26" vspace="5"> </FORM> At the moment, it's an image which gets clicked on but it needs to be the option chosen. I think I can do that with: Code: function gotoPage(s){ var v = s.selectedIndex; var select = document.forms.form.elements.input; // selects question if (v == 1){...} if (v == 2){...} etc. However, as I said, the form's contents must change depending on the option chosen: The form's values which change a Code: <INPUT TYPE=HIDDEN NAME=SubUnitID VALUE="4266"> <INPUT TYPE=HIDDEN NAME=PageID VALUE="1"> Can someone point me in the right direction? Hi I have a entry form which inserts data 2 DB. while the user entering info if he wants to click on any url in left nav pane there should show message: the data won't be saved if you navigate from this page. I have written some code..it works fine but if i Hit submit button on the form It wont submit, still gives the same popup -the data won't be saved if you navigate from this page. HRE IS my code: <script language="javascript"> function closeIt() { return " "; } window.onbeforeunload = closeIt; </script> BUT this works only if i try to navigate from page. But it still prevents the submission. TIA Hello, I have a very simple file upload form, which I'm submitting with javascript whenever the value in the file input changes. I open the Open File.. dialog with javascript too(in IE - in FF the control just has opacity:0 over a button), just by calling click() on it. This works like a charm in both firefox and IE so far, but when I set either the visibility or z-index of the file input control so that it gets hidden, the form doesn't submit in IE(still works fine in FF). The alert fires, so the function is still called, but submitting just doesn't work - nothing received serverside. Anyone know what I'm doing wrong here/what the fix is? Thanks a lot in advance for any help The form looks like this: Code: <form id="form2" runat="server" name="xmluploadform"> <asp:FileUpload ID="xmlupload" onchange="SubmitForm();" runat="server" /> </form> And the SubmitForm function looks like this: Code: function SubmitForm() { alert('submitting'); $('#form2').submit(); } PS. I thought about maybe it was because the browse... button gets hidden so it can't click it, but then is there any way to set the width of it or something? The width of <input type="file"/> is completely different in IE/FF, so it's impossible to make it fit into the design Hello everyone, I have done a lot of research looking for answers on this one but unable to find anything that helps. I have a couple of questions on a page and each are contained in there own form. The questions themselves use checkboxes. I would like the page to not refresh and jump to the top of the page after they submit there answer. So on questions that use radio buttons I have been using Code: <input type="submit" value="Submit" onclick="get_radio_value(); return false;" /> for the submit buttion and that works perfect. I try and use it on questions that use checkboxes and it doesnt work so as a work around I am using the form's action attribute to set it to a link on the page. Here is my form code: Code: <form name="question2" action="#q2">2. <strong>Multiple choice:</strong><a name="q2"></a> Which patient or patients could be transferred to another hospital under the EMTALA Act?<br /> <input type="checkbox" value="a" name="aquestion" />Smith, Bill<br /><input type="checkbox" value="b" name="bquestion" />Wells, Patricia<br /> <input type="checkbox" value="c" name="cquestion" />Hamilton, Larry<br /> <input type="checkbox" value="d" name="dquestion" />Rodriquez, Brad<br /><input type="checkbox" value="e" name="equestion" />Baker, Madison<br /><input type="checkbox" value="f" name="fquestion" />Kahn, Brent<br /> <input type="checkbox" value="g" name="gquestion" />Cahill, Mark<br /><input type="submit" onclick="get_radio2_value()" value="Submit" /></form> <script type="text/javascript" src="first_triage_java_clinical.js"> </script> and here is the javascript code if it helps: Code: function get_radio2_value() { var w = 400; var h = 400; var wleft = (screen.width/2)-(w/2); var wtop = (screen.height/2)-(h/2); var wrong = "<html><head><style type='text/css'> * {margin: 0; padding:0; border:0;}</style>\ <title>Incorrect, try again!</title></head><body><bgsound src='Plbt.wav'>\ <a href='javascript:window.close()'><img src='wrong.jpg'></a></body></html>"; var right = "<html><head><style type='text/css'> * {margin: 0; padding:0; border:0;}</style>\ <title>You are Correct!</title></head><body>\ <a href='javascript:window.close()'><img src='right.jpg'></a></body></html>"; var correct = "false"; if (document.question2.cquestion.checked) { if(document.question2.dquestion.checked) { if(document.question2.equestion.checked) { if(document.question2.fquestion.checked) { if(document.question2.gquestion.checked) { var correct = "true"; } } } } } if (document.question2.aquestion.checked) { var correct = "false"; } if (document.question2.bquestion.checked) { var correct = "false"; } if (correct != "true") { var popup = window.open('','','resizeable=no,scrollbars=no,width=221,height=112, top='+ wtop +', left='+ wleft); popup.document.write(wrong); pops.document.close(); } else { var popup = window.open('','','resizeable=no,scrollbars=no,width=221,height=112, top='+ wtop +', left='+ wleft); popup.document.write(right); pops.document.close(); } } Hey all - I've searched high and low for this through Google, and tried piecing together some solutions, but 1) I'm way too incompetent from a Javascript perspective to take two ideas and make them work and 2) I've spent close to 2 hours and dont have a solution. SOOOO I thought I'd ask the geniuses here for some ideas: I have a page with an iFrame called portalCalcFrame that I'm trying to submit data to to do some calculations and preview in the iFrame before actually submitting the page to the next...well...page (both the "Recalculate" button to send to iFrame and the "Next Step" button to submit it further into the process are on the main frame). So I've got two problems. A) I need to submit a form to a different target, aka portalCalcFrame B) I need to submit the form to a different "action" page than my form actually submits to. (The form submits to a page called step2.php, whereas the iFrame needs to load page calcframe.php and have the form submit to that) I don't really know where to start, Javascript is far from my forte. I've taken it a couple of different ways. Any ideas guys? I love you long time. Thanks in advance! JE I am using an e-commerce solution to run my web business. The checkout portion of the website is COMPLETELY closed off to me and I can't access the files. What I need: A javascript example / solution that will prevent someone from submitting a form without first filling in a field. What I currently have is a series of radio buttons built into the checkout process. It displays 20 options and the customer has to choose which one of the twenty options applies to them. Each customer only has 2 valid options to choose from based on their zip code, but currently the other zip code shipping options are listed as well. I have built a javascript that works great hiding all of the shipping options, taking data from the customer, and then only showing the correct shipping option. The problem is, if the customer doesn't fill this out, then they can just hit submit and pay the default shipping option without ever seeing that they didn't choose the correct zip code. What can I do to prevent them from submitting the form? The submit form is a button and there are 6 other buttons and none of them have any identifying factors. I was curious if there is a method to keep a single input from submitting a form. I have an input into which I'm building a drop down search feature, however, I'd like it so when the user presses return there, instead of submitting the form, it runs an AJAX POST instead. I am currently using keyUp to recognize the button press, but its still submitting the form its attached to. Obviously, I'd like that not to happen. |