JavaScript - Trouble With Simple Javascript Form Validation
I'm trying to make an xhtml form that validates itself through a javascript function. I have the form up but for some reason I can't get it to validate. I'm not even sure if I linked things correctly. Here's what I have:
the xhtml file <?xml version = ″1.0″ encoding = ″utf-8″ ?> <!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"> <head> <script src="gas24.js" type="text/javascript"></script> <h2> Registration Form </h2> <title> Javascript Form Validation Homework </title> </head> <body> <table border=""> <form name="validation_form" method="post" onsubmit="return validate()"> <tr> <td> <t>Name: <input type="text" name="YourName" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> E-mail Address: <input type="text" name="YourEmail" size="10" maxlength="24"/> </td> </tr> </br> <tr> <td> Password: <input type="password" name="YourPassword" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Re-Type Password: <input type="password" name="passwordConfirmed" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Your Gender: <input type="radio" name="MaleBox" Value="Male"> Male <input type="radio" name="FemaleBox" Value="Female"> Female </td> </tr> </br> <tr> <td> Comments: <input type="text" name="Comments" size="100" maxlength="500" value=""/> </td> </tr> <tr> <td> <input type="submit" value="Submit"/> </td> </tr> </form> </table> <p></p> </body> </html> The javascript file: I've tried two things. This: <SCRIPT LANGUAGE="JavaScript"> function validation() { var x=document.forms["validation_form"]["YourName"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } And this: function validation() if ( document.validation_form.YourName.value == "" ) { alert( "Please type your name."); valid = false; } if ( document.validation_form.YourPassword.value =! "document.validation_form.Confirm.value" ) { alert ( "Please confirm your password." ); valid = false; } I would greatly appreciate it if somebody could tell me what I'm doing wrong. Similar TutorialsI'm trying to do a simple validation to see if the field is blank, if it is, I want to write a message to a div. I've added the function call to an onclick. It seems to be set off no matter if there is a value or not, and what's more, the fields are clearing out when the link is clicked. My brain is mush right now, so what am I missing? Code: function validateThis() { document.getElementById('messages').innerHTML = '' var theMessage = ''; var reqMsg = 'must have a value.'; for (var i = 0; i <document.theForm1.elements.length; i++) { if (document.theForm1.elements[i].value = ' ') { theMessage += document.theForm1.elements[i].name +' ' + reqMsg +'<br/>'; }} document.getElementById('messages').innerHTML = theMessage; } Hello, On my client's site: www.twdcycling.com he wanted a place where people could make suggestions for his blog. I accomplished the simple form using a textarea field and even put a little text that clears on clicks and reappears on blur. When you go there--go to the bottom left. It also actually works. The problem is that (besides the fact that so far no one has cared to make a suggestion) somehow the form is (this is what I believe) being submitted automatically. I don't believe a human is clicking submit. When I click submit w/o clicking in the field the default text that I have in the field already gets submitted in the generated email. So I now need to work on my validation in my php file that sends the email. For background I obtained my php file from html-form-guide.com here the file is in its entirety: Code: <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; //Validate first if(empty($name)||empty($visitor_email)) { echo "Name and email are mandatory!"; exit; } if(IsInjected($visitor_email)) { echo "Bad email value!"; exit; } $email_from = 'tom@amazing-designs.com';//<== update the email address $email_subject = "New Form submission"; $email_body = "You have received a new message from the user $name.\n". "Here is the message:\n $message". $to = "tom@amazing-designs.com";//<== update the email address $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; //Send the email! mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); // Function to validate against any email injection attempts function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } ?> It does have some validation code, and it also is set up to handle more parameters than I needed. I tried to just pare it down to the one simple thing (I just need the user to type anything they want into my text area) My reasoning is that I should be able to go get some simple validation snippet to make it so that if there is the possibility something is causing the form to just "fire off" w/o a human clicking, the validation shouldn't allow it to send, cause the text field is empty. But one would think if that is happening my default text would allow it to send, but oddly enough, no! when I get the email (last one at 5:49 am) it was a blank email! So its like some robot is doing two things: clicking in the field to empty it and THEN clicking submit! Weird, I know. But the validation code would fix this if only I knew how. (But on another note, if I try to send an empty box my default text pops back in when I click submit--proving that its happening automatically. I tried all morning yesterday to implement a snippet from several sources. Here's a couple of examples of what I added: Code: function emptyvalidation(entered, alertbox) { // Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } I didn't modify this code at all....maybe where I went wrong here. Should "value" correspond to text area name "message"? (about the only thing I didn't try) Here's another one --this one from W3 schools: Code: function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } this is how it was on the source site, all I changed was "myForm" and "fname" to "blog_suggestion" But when testing both these snippets separately what happened is that on submit I just go to my php page (which is just blank) I'm assuming code I'm adding is crashing the script somehow. And then of course no thank you page and no email sent. Finally here is my current php page in its entirety, followed by the form code on the home page... Code: <?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $message = $_POST['message']; //Validate first if(empty($message)) { echo "Please enter a suggestion before clicking submit."; exit; } $email_from = 'f7digitaldesign@gmail.com';//<== update the email address $email_subject = "SOMEONE HAS SUBMITTED A SUGGESTION FOR THE BLOG!"; $email_body = "\n $message". $to = "f7digitaldesign@gmail.com";//<== update the email address $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . //Send the email! mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); // Function to validate against any email injection attempts function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } ?> I tried to modify the validation I got w/ this to produce the "echo" message "Please enter a suggestion before clicking submit." But let's be honest, by now you know I don't know what in the heck I'm doing (it doesn't seem to matter). Form code: Code: <form name="blog_suggetion" method="post" action="send_form_blogidea.php"> <span class="bloginfotext" ><textarea name="message" rows="14" cols="12" onfocus="clearValue(this, 'Please submit ideas for our blog here—we’d love to hear from you!')" onclick="this.value='';" onblur="if (this.value == '') {this.value = 'Please submit ideas for our blog here—we’d love to hear from you!';}" ></textarea></span> <div style="font-size:6px; color:#FFF;">sdsadfds</div> <input type="submit" name='submit' value="submit"> </form> Any time spent and help offered for this is greatly appreciated!! Also if you need to/want to test the field, I don't care--send me a message. I'll know someone cares! Brian I have built a signup form which has several text inputs and text areas. Their labels are set as their values. When the user focuses on the field, the label text is cleared to accept text input. When focus is changed to another field. The field checks if text has been entered. If it has not, it then resets the value back to the default label value. For example: Code: <input type="text" name="company_name" size="50" class="textInput" value="Company Name" onfocus="if(this.value=='Company Name')this.value='';" onblur="if(this.value=='')this.value='Company Name';" /> What I would like to do is have some simple javascript which checks the fields on submit. If any of the required fields still have the default label value, then I would like to change the colour of the label value in the input to red and disable the form submit until the value is corrected. Most of the inputs and text areas will accept any text, though one is an email text input. I don't think any fancy validation is needed for this email input , other than checking to be sure a '@' has been entered. Since the website that this form will be contained in runs jQuery, I have looked into some plugins for form validation. However, these seem to be over-complicated for what I need. I want to keep this as simple and light as possible. Oh, and also, I am not allowed to use anything php based as this is not allowed to run on our servers for security reasons... Any advice or suggestions are much appreciated! Hey all, I'm finishing up a project at work that has a web-based front end. Our tightly compressed schedule has left me with no time to properly learn Javascript, so I need some help. I have two pages that need client side validation... Page 1: several text inputs, one select, one textarea, and (maybe) a checkbox There are some complex things I could do here, but for now, I just need to make users behave. The textarea must have something in it, certain select options need a Yes/No popup, and if the checkbox is written to the page (ASP determines this) then it must be checked before certain select options are submitted. I could copy some examples I've found, but how do I ignore the checkbox when it doesn't exist? Page 2: two selects and a textarea Options must be selected and the textarea must have something in it. Straightforward, except that it's a dynamic form where each element has a name + i where i is a number that increments each time the user expands the form. Will wildcards work here? I know this looks like "do my homework" but any help would be greatly appreciated. This is desired to work in IE6, but if that can't happen, I can force an IE8 upgrade on everyone. I am trying to have the page go to another page after clicking the submit button. is it possible to add to this function an else statement ? if form is filled then go to this page Code: function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); return false; } return true; } Hi I am trying to valid a simple address, that works fine apart from the fact that it will not allow forward slash in it "/" such as: Unit 12/13 some where. In brief I want to change /^[\w ]+$/; to include a forward character in it. I am new to javascript. many thx. p.s. every time I google it they find me email address validation dehhhhh I use the following code: Quote: function validateVat_No(fld) { var error = ""; var illegalChars = /^[\w ]+$/; // allow letters, numbers, and spaces if (fld.value !== "") { if (!illegalChars.test(fld.value)) { fld.style.background = 'Yellow'; error = "The Vat No contains illegal characters.\n"; } } else { fld.style.background = 'White'; } return error; } I am a javascript begginer and would like to know what is this bit of code saying? (email.indexOf("@",atPos+1) > -1) Thank you! Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Email checker</title> <script type="text/javascript"> function validEmail(email) { invalidChars = " /:,;" if (email == "") { return false; } for (i=0; i<invalidChars.length; i++) { badChar = invalidChars.charAt(i) if (email.indexOf(badChar,0) > -1) { return false; } } atPos = email.indexOf("@",1) if (atPos == -1) { return false; } if (email.indexOf("@",atPos+1) > -1) { return false } periodPos = email.indexOf(".",atPos) if (periodPos == -1) { return false; } return true; } function submitIt(emailForm) { if (!validEmail(emailForm.emailAddr.value)) { alert("Invalid email address"); emailForm.emailAddr.focus(); emailForm.emailAddr.select(); return false } alert("email is correct!"); return true; } </script> </head> <body> <h2>Email checker</h2> <form onsubmit="return submitIt(this)" action="#"> Email Address: <input name="emailAddr" type="text" size="30" /> <p><input type="submit" value="Submit" /> <input type="reset" /></p> </form> </body> </html> Would appreciate some help making some minor enhancements to a pet adoption form: http://pawsct.org/application.php Problem - Applicants don't read. They answer "No" to the "Agree to Shelter Visit" question, then fill out the looooong application, and get abusive when told that they're not eligible for adoption. They apply from Florida and ignore the warnings about the 90 mile limit. Text notes just don't make enough of an impact. I want to use OnChange to give an alert if someone does not answer "Yes" to agree to a shelter visit (i.e. popup "You must agree to a shelter visit to qualify for an adoption from PAWS") and perhaps a warning message (red text reminder about the 90 mile limit next to the drop-down box) if someone enters a state other than CT. Second problem - I'm a volunteer who doesn't know javascript and can't cobble together a SIMPLE, workable solution from other code samples. Any assistance that you can provide would be most welcome and appreciated. Note: we are planning a redesign of the web site and may do some more sophisticated form validation (e.g. check age, valid e-mail, valid phone) in the future. But for now, we're just looking to check a few key fields for answers that would immediately disqualify an applicant. Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript or how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. It'd be great if the submit button could be disabled until all fields are filled correctly, but I don't know if this is possible. Thanks in advance, and please let me know if it'll be possible. :) I've literally tried everything. Read 26 tutorials, interchanged code, etc. My validation functions all work. My AJAX functions work (tested manually using servlet URL's). The second servlet validates the reCaptcha form that's generated on my webpage. After the form is validated, even if everything's correct, nothing happens upon clicking submit. I even have an alert pop up if with the captcha result, just for middle-layer debugging purposes. I want to do all of my validation clientside; none serverside. However, going to be tough if I can't get my god damn form to submit. I've been puzzled by this for close to 36 hours straight. I can't see, and I'm going to get some rest and hope that there is some useful insight on my problem when I return. html form: Code: <form id="f1" name="form1" onsubmit="validate_form(this); return false;" action="register" method="post"> <table cellspacing="5" style="border: 2px solid black;"> <tr> <td valign="top"> <table cellspacing="5"> <tr> <td>*First name</td> <td align="right"><span id="valid_one"></span></td> <td><input type="text" style="width: 320px;" id="fn" name="fn" onBlur="validate_one();"></td> </tr> <tr> <td align="left">*Last name</td> <td align="right"><span id="valid_two"></span></td> <td><input type="text" style="width: 320px;" id="ln" name="ln" onBlur="validate_two();"></td> </tr> <tr> <td align="left">*Email address</td> <td align="right"><span id="result"></span></td> <td><input type="text" style="width: 320px;" id="mailfield" name="email" onBlur="startRequest();"></td> </tr> <tr> <td align="left">*Phone number</td> <td align="right"><span id="valid_three"></span></td> <td><input type="text" style="width: 320px;" id="pn" name="pn" onBlur="validate_three();"></td> </tr> <tr> <td align="left">*City/Town</td> <td align="right"><span id="valid_four"></span></td> <td><input type="text" style="width: 320px;" id="c" name="c" onBlur="validate_four();"></td> </tr> <tr> <td></td> <td></td> <td> <select name="s"> <option value="AL">Alabama <option value="AK">Alaska <option value="AZ">Arizona <option value="AR">Arkansas <option value="CA">California <option value="CO">Colorado <option value="CT">Connecticut <option value="DE">Delaware <option value="FL">Florida <option value="GA">Georgia <option value="HI">Hawaii <option value="ID">Idaho <option value="IL">Illinois <option value="IN">Indiana <option value="IA">Iowa <option value="KS">Kansas <option value="KY">Kentucky <option value="LA">Louisiana <option value="ME">Maine <option value="MD">Maryland <option value="MA">Massachusetts <option value="MI">Michigan <option value="MN">Minnesota <option value="MS">Mississippi <option value="MO">Missouri <option value="MT">Montana <option value="NE">Nebraska <option value="NV">Nevada <option value="NH">New Hampshire <option value="NJ">New Jersey <option value="NM">New Mexico <option value="NY">New York <option value="MC">North Carolina <option value="ND">North Dakota <option value="OH">Ohio <option value="OK">Oklahoma <option value="OR">Oregon <option value="PA">Pennsylvania <option value="RI">Rhode Island <option value="SC">South Carolina <option value="SD">South Dakota <option value="TN">Tennessee <option value="TX">Texas <option value="UT">Utah <option value="VT">Vermont <option value="VA">Virginia <option value="WA">Washington <option value="WV">West Virginia <option value="WI">Wisconsin <option value="WY">Wyoming </select> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td></td> <td></td> <td><span id="error"></span></td> </tr> <tr> <td valign="top">*Anti-Spam Verification</td> <td></td> <td id="reCaptcha"></td> </tr> </table> </td> <td valign="top"> <table cellspacing="5"> <tr> <td align="left">*Affiliation</td> <td align="right"><span id="valid_five"></span></td> <td><input type="text" style="width: 320px;" id="affl" name="affl" onBlur="validate_five();"></td> </tr> <tr> <td align="left">*Research Area:</td> <td align="right"><span id="valid_six"></span></td> <td><input type="text" style="width: 320px;" id="ra" name="ra" onBlur="validate_six();"></td> </tr> <tr> <td valign="top" align="left">*Research Overview</td> <td align="right"><span id="valid_seven"></span></td> <td><textarea cols="38" rows="6" id="ro" name="ro" onKeyDown="limitText(this.form.ro,this.form.countdown,500)" onKeyUp="limitText(this.form.ro,this.form.countdown,500)" onBlur="validate_seven();"></textarea></td> </tr> <tr> <td></td> <td></td> <td><font size="1">You have <input readonly type="text" name="countdown" size="1" value="500"> characters remaining.</font></td> </tr> <tr> <td align="left">*Talk Availability</td> <td></td> <td> <input type="radio" name="ta" value="In person">In person <input type="radio" name="ta" value="Online">Online <input type="radio" name="ta" value="Both" checked>Both </td> </tr> <tr> <td align="left" valign="top">Links</td> <td></td> <td> <table id="linkTable" border="0"> <td><input type="text" style="width: 320px;" name="link"></td> <td><div id="result"></div></td> </table> </td> <td align="left" valign="top"><input type="button" value="Add Link" onclick="addLink('linkTable')"></td> </tr> <tr> <td></td> <td><span style="color: red;"></span></td> </tr> </table> </td> </tr> </table> <br /> <input type="submit" id="submit" name="submit" value="Submit Form"> </form> Javascript file: Code: /* * script.js - ajax and table functions */ var xmlHttp; // global instance of XMLHttpRequest var xmlHttp2; // second for captcha functions var validAjax = new Boolean(); var validCaptcha = new Boolean(); var valid_one = new Boolean(); var valid_two = new Boolean(); var valid_three = new Boolean(); var valid_four = new Boolean(); var valid_five = new Boolean(); var valid_six = new Boolean(); var valid_seven = new Boolean(); function init() { showRecaptcha('reCaptcha'); // Separate booleans for AJAX funcs validAjax = false; validCaptcha = false; // Booleanse for fields that don't require servlet validation valid_one = false; valid_two = false; valid_three = false; valid_four = false; valid_five = false; valid_six = false; valid_seven = false; } function showRecaptcha(element) { Recaptcha.create("6Le1a8ESAAAAAGtxX0miZ2bMg0Wymltnth7IG-Mj", element, {theme: "red", callback: Recaptcha.focus_response_field}); } function validate_form() { if (valid_one && valid_two && valid_three && valid_four && validEmail) { startCaptchaRequest(); if (validCaptcha) { return true; } } else { alert("Submission contains errors. Please fill out all required fields before submitting."); return false; } } function validate_one() { if (document.getElementById("fn").value == 0) { valid_one = false; document.getElementById("valid_one").innerHTML = "No"; } else { valid_one = true; document.getElementById("valid_one").innerHTML = ""; } } function validate_two() { if (document.getElementById("ln").value == 0) { valid_two = false; document.getElementById("valid_two").innerHTML = "No"; } else { valid_two = true; document.getElementById("valid_two").innerHTML = ""; } } function validate_three() { if (document.getElementById("pn").value == 0) { valid_three = false; document.getElementById("valid_three").innerHTML = "No"; } else { valid_three = true; document.getElementById("valid_three").innerHTML = ""; } } function validate_four() { if (document.getElementById("c").value == 0) { valid_four = false; document.getElementById("valid_four").innerHTML = "No"; } else { valid_four = true; document.getElementById("valid_four").innerHTML = ""; } } function validate_five() { if (document.getElementById("affl").value == 0) { valid_five = false; document.getElementById("valid_five").innerHTML = "No"; } else { valid_five = true; document.getElementById("valid_five").innerHTML = ""; } } // //function validate_six() { // if (document.getElementById("ra").value == 0) { // valid_six = false; // document.getElementById("valid_six").innerHTML = "No"; // } // else { // valid_six = true; // document.getElementById("valid_six").innerHTML = ""; // } //} // //function validate_seven() { // if (document.getElementById("ro").value == 0) { // valid_seven = false; // document.getElementById("valid_seven").innerHTML = "No"; // } // else { // valid_seven = true; // document.getElementById("valid_seven").innerHTML = ""; // } //} function addLink(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "text"; element1.name = "link" + rowCount; element1.style.width = "320px"; cell.appendChild(element1); } function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } function createXmlHttpRequest() { if(window.ActiveXObject) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } } function startRequest() { createXmlHttpRequest(); var param1 = document.getElementById('mailfield').value; if (param1 == "") { validEmail = false; document.getElementById("result").innerHTML = "Blank"; } else { xmlHttp.open("GET", "http://localhost:1979/PolarSpeakers/servlet/mailCheck.do?e=" + param1, true) xmlHttp.onreadystatechange = handleStateChange; xmlHttp.send(null); } } function handleStateChange() { if(xmlHttp.readyState==4) { if(xmlHttp.status==200) { var message = xmlHttp.responseXML .getElementsByTagName("valid")[0] .childNodes[0].nodeValue; if (message == "Unregistered") { validEmail = true; document.getElementById("result").style.color = "green"; } else { validEmail = false; document.getElementById("result").style.color = "red"; } document.getElementById("result").innerHTML = message; } else { alert("Error checking e-mail address - " + xmlHttp.status + " : " + xmlHttp.statusText); } } } function createCaptchaRequest() { if(window.ActiveXObject) { xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp2=new XMLHttpRequest(); } } function startCaptchaRequest() { alert('made it to captcha requeswt'); createCaptchaRequest(); var param1 = Recaptcha.get_challenge(); var param2 = Recaptcha.get_response(); xmlHttp2.open("POST", "http://localhost:1979/PolarSpeakers/servlet/captchaCheck.do?c=" + param1 + "&r=" + param2, true) xmlHttp2.onreadystatechange = handleStateChangeCaptcha; xmlHttp2.send(null); } function handleStateChangeCaptcha() { if(xmlHttp2.readyState==4) { if(xmlHttp2.status==200) { var message = xmlHttp2.responseXML .getElementsByTagName("result")[0] .childNodes[0].nodeValue; if (message == "Valid") { alert("captcha valid"); validCaptcha = true; } else { document.getElementById("error").innerHTML = message; validCaptcha = false; } } else { alert("Error checking captcha validity - " + xmlHttp2.status + " : " + xmlHttp2.statusText); } } } Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> I have been working on this code for a few days now. It is suppose to: 1. Remove the default values placed in the textarea. 2. Enter only numbers in the Phone Number field. 3. Verify that the passwords entered in the password fields are the same. 4. Verify everything is filled out, one of the radio buttons is selected and at least one of the check boxes are checked using a Submit() function as well as clear the fields using a Reset() function. I have the first two figured out and was able to get the password to verify once but can not get it to work again with any code. I am also unable to figure out a code that will call all these funtions together in the end to verify everything is filled out and not have the default words count as the field being filled. The idea of a default text is also kind of strange to me. I figured out how to remove the text entered as the value, but how do you get JavaScript to know that is the default and not an option to be used? 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" /> <title>Registration</title> <!--Create a registration form, similar to what you may encounter when registering for an online Web site. Include three sections: Personal Information, Security Information, and Preferences. In the Personal Information section, add name, e-mail address, and telephone fields. Include default text in the name and e-mail text boxes, but write some code that removes the default text from each text box when a user clicks it. Write code for the telephone field that prevents users from entering any values except for numbers. In the Security Information section, add password and password confirmation fields. Write code that ensures that the same value was entered into both fields. Also add a security challenge question selection list and a security answer text box that the Web site will use to help identify a user in the event that he or she loses his or her password. The security challenge selection list should contain questions such as What is your mother's maiden name?, What is the name of your pet?, and What is your favorite color?. In the Preferences section, add radio buttons that confirm whether a user wants special offers sent to his or her e-mail address. Also, include check boxes with special interests the user may be interested in, such as entertainment, business, and shopping. Add submit and reset buttons that call submit() and reset() event handler functions when they are clicked. The submit() event handler function should ensure that the user has entered values into each text box, and that the values submitted are not the same as the default text. The submit() event handler function should also ensure that the user selects a security challenge question, selects a radio button to confirm whether he or she wants special offers sent to his or her e-mail address, and selects at least one interest check box. Submit the form to the FormProcessor.html script (there is a copy in your Cases folder for Chapter 5). Save the document as Registration.html. --> <script language="javascript" type="text/javascript"> // This JavaScript removes default values form field function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = "" } } // This JavaScript allows characters exept numbers function AcceptLetters(objtextbox) { var exp = /[^\D]/g; objtextbox.value = objtextbox.value.replace(exp,''); } // This JavaScript allows numbers only function AcceptDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,''); } //This JavaScript confirms everything is filled out function confirmSubmit() { var submitForm = window.confirm("Are you sure you want to submit the form?"); if (document.registar[0].name.value == "Name" || document.registar[0].name.value == "" || document.registar[0].e_mail.value == "E-Mail Address" || document.registar[0].e_mail.value == "" || document.registar[0].phone.value == "" || document.registar[0].phone.value == "" || document.registar[0].password1.value == "" || document.registar[0].password2.value == "" || document.registar[0].sq_answer.value == "Question Answer") { window.alert("You must enter all fields above."); return false; } else return true; } </script> </head> <body> <h1>Registration Page</h1> <form name="registar " method="post" onsubmit="return confirmSubmit()"> <h3>Personal Information</h3> Name:<br /> <input type="text" name="name" value="Name" maxlength=10 id="letters" onFocus="doClear(this)" onkeyup="AcceptLetters(this)" /> <br /> E-Mail:<br /> <input type="text" name="email" value="E-mail Address" onFocus="doClear(this)" /> <br /> Phone Number:<br /> <input type="text" name="phoneNumber" maxlength=10 id="txttest" onFocus="doClear(this)" onkeyup="AcceptDigits(this)" /> <br /> <h3>Security Information</h3> Password:<br /> <input type="password" name="password1" /><br /> Confirm Password:<br /> <input type="password" name="password2" /><br /> <DIV ID="password_result"> </DIV> Security Question:<br /> <select id="selection"><br /> <option value=0>Please Choose One</option> <option value=1>What is your favorite food?</option> <option value=2>What is your Mother's maiden name?</option><br /> <option calue=3>What is your pets name?</option><br /> <option value=4>What is the name of your High School?</option><br /> </select><br /> Answer<br /> <input type="text" name="sq_answer" value="Question Answer" onFocus="doClear(this)" /><br /> <h3>Preferences</h3> Yes<input type="radio" name="confirmAnswer" value="Yes"/>No<input type="radio" name="answer" value="No" />Would you like any special offers sent to your E-mail address?<br /> <h5>Interests</h5> <input type="checkbox" name="interest" value="check"/>Entertainment<br /> <input type="checkbox" name="interest" value="check"/>Shopping<br /> <input type="checkbox" name="interest" value="check"/>Business<br /> <input type="checkbox" name="interest" value="check"/>Exercise<br /> <br /> <input type="submit" value="Submit"/> <input type="reset" value="Reset"/> </form> </body> </html> Hi all, I am new to JS and usually learn by studying code posted online and modify it to have it do what I need. Recently, I used a totaling plugin for an online ordering form which does the below: item1 qty(user input text) * preset price = total price item2 qty(user input text) * preset price = total price item3 qty(user input text) * preset price = total price -------------------------------------------------------- grand total -------------------------------------------------------- The JS code which passes the grandTotal variable is as below: Code: function ($this){ // sum the total of the $("[id^=total_item]") selector var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits "₹" + sum.toFixed(2) ); } The problem I have is the above grandTotal displays the final value when put into a table like below: Code: <td align="right" id="grandTotal"></td> But I am unable to make it work by passing it into a variable within the form fields. I would like to do something like this: Code: <input type="text" name="grandTotal" id="grandTotal" readonly="readonly" /> Can somebody please help me fix this? Any help will be greatly appreciated. Thank you. could anyone tell me how to do this? i don't know anything about javascript, but it is the most elegant way to validate a form. i have 2 questions asked in a form (name=questions). First question are radio buttons with 3 answers (name=answer). Second is a questions with a numeric value as answer with max 10 characters (name=questionb). Could anyone tell me where to start? Thanks, Walter I have a form developed in Dreamweaver CS5 using Spry Assets, I have 2 required fields in the form. One is email the other is phone. I want the user to only have to fill in one or the other, but one or the other needs to be filled out. Here is the form code: [code]<form id="form1" name="form1" method="post" action="http://www.greenhousegraphix.com/GatewayVentures/sendmail.php"> <span id="sprytextfield1"><label>Name</label> <input name="Name" type="text" id="Name" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span></span><br /> <span id="sprytextfield3"><label>Title</label> <input name="Title" type="text" id="Title" size="45" /> </span><br /> <span id="sprytextfield2"><label>Company</label> <input name="Company" type="text" id="Company" size="45" /> </span><br /> <span id="sprytextarea1"><label>Address</label> <textarea name="Address" id="Address" cols="39" rows="2"></textarea> </span><br /> <span id="sprytextfield4"><label>City</label> <input name="City" type="text" id="City" size="45" /> </span><br /> <span id="sprytextfield5"><label>State</label> <input name="State" type="text" id="State" size="45" /> </span><br /> <span id="sprytextfield6"><label>Zip</label> <input name="Zip" type="text" id="Zip" size="45" /> <span class="textfieldInvalidFormatMsg">Invalid format.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMinValueMsg">The entered value is less than the minimum required.</span></span><br /> <span id="sprytextfield7"><label>Phone</label> <input name="Phone" type="text" id="Phone" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextfield8"><label>Email</label> <input name="Email" type="text" id="Email" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextarea2"><label>Message</label> <textarea name="Message" id="Message" cols="39" rows="6"></textarea> </span><br /> <input name="SUBMIT" type="image" class="marginleft95px" src="images/submit.jpg" /> </form> </div> <div id="apDiv2"><img src="images/contact-us-keyboard.jpg" width="318" height="230" alt="contact us" /></div> <div id="apDiv3"><img src="images/contact-us.jpg" width="318" height="230" alt="contact us" /></div> </div></div> <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["blur"]}); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {isRequired:false}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none", {isRequired:false}); var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none", {isRequired:false}); var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5", "none", {isRequired:false}); var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6", "zip_code", {isRequired:false}); var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7", "phone_number", {validateOn:["blur"], hint:"(999) 999-9999"}); var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8", "email", {validateOn:["blur"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {isRequired:false}); var sprytextarea2 = new Spry.Widget.ValidationTextarea("sprytextarea2", {isRequired:false}); </script>[code] Please help!! Hi there! Could somebody please help me understand why this javascript isn't executing? I've been stuck with it for days and have researched the problem to death to no avail. Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Form</title> <script type="text/javascript"> function allComplete() { var result = true; var numbers = document.getElementsById('numbers'); for(var number in numbers) { if(number.value == null) { result = false; break; } } if(result == false) { alert("Please fill in all the fields"); return result; } return result; } </script> </head> <body> <h3>In each field enter a number of your choice!</h3> <form action="php.php" method="GET"> <input type="text" name="numbers[]" id="numbers" size="4" /><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="text" name="numbers[]" id="numbers" size="4"/><br/> <input type="submit" name="submit" onSubmit="return allComplete()" value="Enter"/><br/> </form> </body> </html> Thanks very much in advance. Hello, I am using the following javascript to validate a text field on my site: Code: function checkExpire(form) { // regular expression to match required date format re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if(form.txtExpire.value != '' && !form.txtExpire.value.match(re)) { alert("Invalid date format: " + form.txtExpire.value); form.txtExpire.focus(); return false; } return true; } The above code works fine for the following situations: The default value of the field is: __/__/____ The JavaScript code above will not accept that for a field value. If a user inputs the following for a date 5_/7_/11__ for May 7th, 2011 the JavaScript will not accept the format it must be entered as: 05/07/2011 (in order to clear the validation)... NOW HERE IS WHAT I NEED THE JAVASCRIPT TO DO: 1) It needs to accept __/__/____ as a value that can be inserted into the database 2) still retains the code above so 5_/7_/11__ is not an acceptable date but 05/07/2011 will work just fine 3) Now... the default value of the text field in Internet Explorer is __/__/____ but the value is blank in Mozilla Firefox so in an instance where the text field is completely blank I need the JavaScript to assign the value '__/__/____' ... SO FAR: I did at one point get both the validation working so it worked for rules 1 and 2 mentioned above but I completely destroyed it while trying to integrate rule 3 into the functionality. So I know this can be accomplished with a series of if / else statements as well as assigning a value to a form object to handle rule# 3 ... I am just a novice getting ready to turn intermediate in JavaScript so any help, guidance, reference or example / sample code you could give me would be much appreciated. Thank your for your assitance and I hope you are all doing well. Cordially, aRK Hi i need help with an assignment that validates forms using javascript. Using my instructors example as a guide, i wrote this if you click submit on the example it properly returns false and displays an error message, in my assignment it does nothing but submit to the echo while im trying to get an error message. The assignment is unfinished but i wanted to test out the first bit of code and its not working. |