JavaScript - Js Form Field Validations Functions
use in form fields - onBlur="chkalpha(this)"
function chknum(field) { var valid = "0123456789"; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only numeric data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalpha(field) { var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphabetic data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalphanum(field) { var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_-. "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphanumeric data is accepted!"); field.value=""; field.focus(); field.select(); } } Similar TutorialsI have been working on a JavaScript form with validation and I cant get it to work right. The form is supposed to validate the name, E-mail, Phone number, Password and confirmation, Drop-down selection, Question reply, yes and no radios, and 3 preferences check-boxes. It is also supposed to verify that the passwords match, not allow any letters or special characters in the phone number box, and remove the default text when a user clicks on the Name, E-mail, and Question reply boxes. I've been checking over the code for almost a month now and I can't figure out why it is not working. This is my entire code. [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>Contact</title> <script type="text/javascript"> /* <![CDATA[ */ function onlyDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,""); } function textdisappear(txt) { if (txt.value == txt.defaultValue) { txt.value = "" } function passmatch() { if (document.forms[0].psswrd2.value != document.forms[0].psswrd1.value) { window.alert("You did not enter the same password!"); document.forms[0].psswrd1.focus(); } function validate() { var name = document.form1.Name; var email = document.form1.Email; var phone = document.form1.Telephone; var question = document.form1.selection; var reply = document.form1.questionreply var word1 = document.form1.psswrd1 var word2 = document.form1.psswrd2 var chkradio = false; var chkbox = false; if (name.value == "") { window.alert("Name please."); name.focus(); return false; } if (email.value == "") { window.alert("E-mail is blank."); email.focus(); return false; } if (email.value.indexOf("@", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if (email.value.indexOf(".", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if ((phone.value == "")) { window.alert("Telephone number please."); phone.focus(); return false; } if (word1.value == "") { window.alert("Password please."); word1.focus(); return false; } if (word2.value == "") { window.alert("Re-type password please."); word2.focus(); return false; } if (question.selectedIndex < 1) { alert("Choose question please."); question.focus(); return false; } if (reply.value == "" || reply.value == "Question reply") { window.alert("Question reply please."); reply.focus(); return false; } for (var i=0; i<2; ++i) { if (document.form1.confirmreply.checked == true) { chkradio = true; break; } if (chkradio != true) { window.alert("Yes or no please."); confirmrelpy.focus(); return false; } for (var i=0; i<3; ++i) { if (document.form1.hobby.checked == true) { chkbox = true; break; } if (chkbox != true) { window.alert("Choose preference."); hobby.focus(); return false; } return true; } /* ]]> */ </script> </head> <body> <center><h1>Contact</h1></center> <form method="post" action="mailto:someemail@somedomain.com" name="form1" onsubmit="return validate();"> <h3>Your Details</h3> <p>Name:* <input type="text" name="Name" value="Enter Name" onfocus="textdisappear(this)" ></p> <p>E-mail:* <input type="text" name="Email" value="Enter E-mail" onfocus="textdisappear(this)" ></p> <p>Phone Number:* <input type="text" name="Telephone" onkeyup="onlyDigits(this)"><br> <br /> <h3>Password and Secret Question</h3> Password:<br /> <input type="password" name="psswrd1" value="" />*<br /> Confirm:<br /> <input type="password" name="psswrd2" value="" onblur="passmatch()" />*<br /> <p>Choose a question:*<br /> <select type="text" value="" name="selection"> <option> </option> <option>Where was your elementary school?</option> <option>Who was the first person you ever kissed?</option> <option>What was your first car?</option> <option>Who is your favorite author?</option> </select><br /> reply<br /> <input type="text" name="questionreply" value="Question reply" onfocus="textdisappear(this)" />*<br /> <h3>Offers</h3> Do you want any special offers sent to you?*<br /> Yes<input type="radio" name="confirmreply" value="Yes"/>No<input type="radio" name="confirmreply" value="No" /> <h3>Which preference do you have?*</h3> <input type="checkbox" name="hobby" value="check"/>Inside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Outside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Both<br /> <br /> <p><input type="submit" value="Submit" name="submit" /> <input type="reset" value="Reset" name="reset"></p> </form> </body> </html> [CODE] Hi Guys, Someone please help me how to add new function to remove the field, i have js script function that add new field as follows Code: <script language="javascript"> fields = 0; function addInput() { if (fields != 10) { var htmlText = " <input type='text' name='friends[]' value='' size='auto' maxlength='45' /><br />"; var newElement = document.createElement('div'); newElement.id = 'new_field'; newElement.innerHTML = htmlText; var fieldsArea = document.getElementById('new_field'); fieldsArea.appendChild(newElement); fields += 1; } else { alert("Only 10 fields allowed."); document.form.add.disabled=true; } } </script> but i need some helps to add new functions for removing field, For any suggest and pointer would be appreciate. Code: <?php if (isset($_COOKIE["ValidUserAdmin"])) { require "config1.php"; require "config.php"; include "header_vendor.php"; $auth = ($_COOKIE["ValidUserAdmin"]); $sys_date= date("m/d/YY"); $sys_date1= date("Y/m/d"); ?> <html> <head> </head> <body> <table id="page"> <tr><td> <br> <form id="form1" name="form1" method="POST" > <TABLE class="tbl" width="100%" ALIGN="CENTER" CELLPADDING="0" CELLSPACING="1" BGCOLOR="#E4EEE3"> <TR> <TD colspan="4"><strong>Add New vendor </strong></a></TD> </TR> <TR> <TD BGCOLOR="#FFFFFF">Vendor Name <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <input type="text" name="ven_name" value="ven_name" size="40" ></TD> <TD BGCOLOR="#FFFFFF">Category <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <? $query1 = "SELECT distinct Vendor_category from aa_customize where Vendor_category != ''"; $result1 = mysql_query($query1); if(!$result1) { echo "The query failed " . mysql_error(); } else { echo "<select name='category' >"; ?> <option value=""> Select One </option> <? while($row = mysql_fetch_array($result1, MYSQL_ASSOC)) { $select= $row['Vendor_category']; echo"<option value='". $row['Vendor_category']."'>" .$row['Vendor_category'] . "</option>"; } echo"</select>"; } ?></TD> </TR> <TR><TD colspan="4"><strong>Contact Details </strong></TD></TR> <tr> <TD BGCOLOR="#FFFFFF">Contact Landline No. <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <input type="TEXT" name="landline" value="" size="15"> </TD> <TD BGCOLOR="#FFFFFF">Contact Mobile <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <INPUT id="mobile" NAME="mobile" TYPE="text" value="" size="15" /></TD> </TR> <TR> <TD BGCOLOR="#FFFFFF">Contact Email <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <input type="TEXT" name="email" size="35" value=""> </TD> <td bgcolor="#FFFFFF">Website</td> <td bgcolor="#FFFFFF"> <input type="text" name="website"></td> </TR> <TR> <TD BGCOLOR="#FFFFFF">Address<span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF" colspan="3"><p> <textarea white-space:nowrap;overflow:auto; rows="3" cols="35" type="TEXT" name="address"><? echo $address ; ?></textarea></p> </TD> </TR> <TR> <TD BGCOLOR="#FFFFFF">State<span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <? $query1 = "SELECT distinct state from subcategory order by cat_id"; $result1 = mysql_query($query1); if(!$result1) { echo "The query failed " . mysql_error(); } else { echo "<select name='state' onChange='AjaxFunction(document.form1.state.options[document.form1.state.selectedIndex].text);'>"; ?> <option value=""> Select One </option> <? while($row = mysql_fetch_array($result1, MYSQL_ASSOC)) { $select= $row['state']; echo"<option value='". $row['state']."'>" .$row['state'] . "</option>"; } echo"</select>"; } ?> <TD BGCOLOR="#FFFFFF">City <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <select name="city"> </select> </TR> <TR> <TD BGCOLOR="#FFFFFF">Country <span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <select name="country"> <option value="India" selected="selected">India</option> <option value="United States">United States</option> <option value="United Kingdom">United Kingdom</option> </select> <TD BGCOLOR="#FFFFFF">Pincode<span style="color:#FF0000"> * </span></TD> <TD BGCOLOR="#FFFFFF"> <input type="TEXT" name="pin" size="8" value="" ></TD> </TR> <tr><td colspan="4"><strong>Mode Of Transaction</strong></td> </tr> <tr><td bgcolor="#FFFFFF" ><label> <input type="checkbox" id="check1" name="cheque" value="Cheque" onClick="showMe('chq_div','pay_chq', this)" /> Cheque/AtparCheque</label></td> <td colspan="3" bgcolor="#FFFFFF"><div id="chq_div" style="display:none"> In Favour Of <input id="pay_chq" type="TEXT" name="payment_to_chq" size="30" ></div> </td></tr> <tr><td bgcolor="#FFFFFF"><label> <input type="checkbox" id="check2" name="dd" value="DD" onClick="showMe1('dd_div','pay_dd','pay_at',this)"/> Demand Draft</label></td> <td colspan="3" bgcolor="#FFFFFF"><div id="dd_div" style="display:none"> In Favour Of <input id="pay_dd" type="TEXT" name="payment_to_dd" size="30" > Payable At <input id="pay_at" type="TEXT" name="payable_at" size="30" > </div></td> </tr> <tr><td bgcolor="#FFFFFF"><label> <input type="checkbox" id="bktransfer" name="banktransfer" value="Bank Transfer" onClick="showMe2('addBank', this)"/> Bank Transfer</label></td> <td colspan="3" bgcolor="#FFFFFF"> <table id="addBank" style="display:none"> <tr><td BGCOLOR="#E4EEE3" align="center">Account Name</td><td BGCOLOR="#E4EEE3" align="center">Account No.</td><td BGCOLOR="#E4EEE3" align="center">Bank Name</td><td BGCOLOR="#E4EEE3" align="center">Branch Name</td><td BGCOLOR="#E4EEE3"><input type="button" name="add" value="Add Bank" onClick="addRow('addBank')"></td></tr> </table> </td></tr> <tr><td bgcolor="#FFFFFF"><label> <input type="checkbox" id="cash" name="cash" value="Cash" /> Cash</label></td> <td colspan="3" bgcolor="#FFFFFF"> </td></tr> <!-- flooble Expandable Content box start --> <tr><td align="left" colspan="4">[<a title="show/hide" id="exp1254911560_link" href="javascript: void(0);" onClick="toggle(this, 'exp1254911560');"> - </a>] <b>Add Contanct Persons</b></td> </tr> <tr><td bgcolor="#FFFFFF" colspan="4"> <table id="exp1254911560"> <tr><td align="center">Name</td><td align="center">Contact No</td><td align="center">Email Id</td><td align="center">Designation</td><td align="center">Department</td><td><input type="button" name="add" value="Add contanct" onClick="addRow1('exp1254911560')"></td></tr> </table> </td> </tr> <script language="javascript">toggle(getObject('exp1254911560_link'), 'exp1254911560');</script> <!-- flooble Expandable Content box end --> <TR> <TD colspan="4" align="center" bgcolor="E4EEE3" > <input name="submit" type="SUBMIT" value="Add" align="middle" size="30" onClick="return validate();"></TD> </TR> </TABLE> </form> <script language="JavaScript" type="text/javascript"> function validate(){ var rgxa = /^-?\d+(\.\d+)?$/; dml=document.forms['form1']; // get the number of elements from the document len = dml.elements.length; for( i=0 ; i<len ; i++) { //check the textbox with the elements name if (dml.elements[i].name=='bank[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Bank Name "); dml.elements[i].focus(); return false; } } if (dml.elements[i].name=='branch[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Branch Name "); dml.elements[i].focus(); return false; } }if (dml.elements[i].name=='account[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Account No "); dml.elements[i].focus(); return false; } if(!rgxa.test(dml.elements[i].value)) { alert("Not a Valid Account no, Enter in Numerics!!"); dml.elements[i].value=""; dml.elements[i].focus(); return false; } } if (dml.elements[i].name=='account_name[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Account Name "); dml.elements[i].focus(); return false; } } if (dml.elements[i].name=='user[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the User Name "); dml.elements[i].focus(); return false; } } if (dml.elements[i].name=='contact[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Contact No "); dml.elements[i].focus(); return false; } if(!rgxa.test(dml.elements[i].value)) { alert("Not a Valid Contact no, Enter in Numerics!!"); dml.elements[i].value=""; dml.elements[i].focus(); return false; } } if (dml.elements[i].name=='emailid[]') { // if exists do the validation and set the focus to the textbox if (dml.elements[i].value=="") { alert("Enter the Email Id "); dml.elements[i].focus(); return false; } } } var frmvalidator = new Validator("form1"); var chq_select = document.getElementById("check1") var chq_fvr = document.getElementById("pay_chq") var dd_select = document.getElementById("check2") var dd_fvr = document.getElementById("pay_dd") var dd_at = document.getElementById("pay_at") var bank_select = document.getElementById("bktransfer") var cash_select = document.getElementById("cash") frmvalidator.addValidation("ven_name","req","Please Enter Vendor Name"); frmvalidator.addValidation("ven_name","maxlen=200"); frmvalidator.addValidation("category","req","Please Select category for Vendor"); frmvalidator.addValidation("landline","req","Please enter your Landline no."); frmvalidator.addValidation("landline","maxlen=15","Landline no. exceeds its maximum length"); frmvalidator.addValidation("landline","numeric","Only digits are allowed in landline no"); frmvalidator.addValidation("mobile","req","Please enter your Mobile no."); frmvalidator.addValidation("mobile","maxlen=13","Mobile no. exceeds its maximum length"); frmvalidator.addValidation("mobile","numeric","Only digits are allowed in Mobile no"); frmvalidator.addValidation("email","email","please Enter Valid Email-Id"); frmvalidator.addValidation("email","maxlen=100"); frmvalidator.addValidation("email","req","Please Enter your Email-Id"); frmvalidator.addValidation("address","req","Please Enter your Address"); frmvalidator.addValidation("address","maxlen=800","Address Field exceeds its maximum length"); frmvalidator.addValidation("city","req","Please select your city"); frmvalidator.addValidation("city","maxlen=100","maximum length allowed for city is 100 alphabets"); frmvalidator.addValidation("state","req","Please select your State"); frmvalidator.addValidation("state","maxlen=100","maximum length allowed for State is 150 alphabets"); frmvalidator.addValidation("country","req","Please select your Country"); frmvalidator.addValidation("country","maxlen=100","maximum length allowed for Country is 150 alphabets"); frmvalidator.addValidation("pin","req","Please enter Your Pin code"); frmvalidator.addValidation("pin","maxlen=6","Pin code must be of 6 digits"); frmvalidator.addValidation("pin","minlen=6","Pin code must be of 6 digits"); frmvalidator.addValidation("pin","numeric","Pin code must be digit"); if(chq_select.checked == false && dd_select.checked== false && bank_select.checked== false && cash_select.checked==false) { alert("Select One mode of Payment"); return false; } if(chq_select.checked == true && chq_fvr.value=="") { chq_fvr.focus(); alert("Enter Cheque In Favour Of"); return false; } if(dd_select.checked == true && dd_fvr.value=="") { dd_fvr.focus(); alert("Enter DD In Favour Of"); return false; } if(dd_select.checked == true && dd_at.value=="") { dd_at.focus(); alert("Enter DD Payable at "); return false; } } </script> <BR> <? $ban = $_POST['bank']; $branch = $_POST['bank']; $v_name=$_POST['ven_name']; if(isset($_POST['submit']) && isset($_POST['banktransfer']) ) { $str="INSERT INTO aa_vendor1(id,ven_name,category,landline,mobile,email,address,city,state,country,pin,cheque,cash,dd,banktransfer,chq_favr,dd_favr,dd_pay,website) VALUES ('','".$_POST['ven_name']."','".$_POST['category']."','".$_POST['landline']."','".$_POST['mobile']."','".$_POST['email']."','".$_POST['address']."','".$_POST['city']."','".$_POST['state']."','".$_POST['country']."','".$_POST['pin']."','".$_POST['cheque']."','".$_POST['cash']."','".$_POST['dd']."','".$_POST['banktransfer']."','".$_POST['payment_to_chq']."','".$_POST['payment_to_dd']."','".$_POST['payable_at']."','".$_POST['website']."')"; mysql_query($str); echo mysql_error(); $bak = $_POST['bank']; $brnch = $_POST['branch']; $acc_name = $_POST['account_name']; $acc_no = $_POST['account']; $count = count($bak); for($i=0 ; $i < count($ban); $i++) { $qry = "INSERT INTO aa_bank (`id`,`acc_name`,`acc_no`,`bank`,`ven_name`,`branch_name`) VALUES ('','".$acc_name[$i]."','".$acc_no[$i]."','".$bak[$i]."','".$_POST['ven_name']."', '".$brnch[$i]."')"; mysql_query($qry); echo mysql_error(); } $desg = $_POST['desg']; $user = $_POST['user']; $contact = $_POST['contact']; $emailid = $_POST['emailid']; $dept = $_POST['dept']; $count11 = count($desg); for($i=0 ; $i < count($desg); $i++) { $qry = "INSERT INTO contacts (`id`,`ven_name`,`desg`,`namee`,`contact`,`emailid`,dept) VALUES ('','".$_POST['ven_name']."','".$desg[$i]."','".$user[$i]."','".$contact[$i]."', '".$emailid[$i]."','".$dept[$i]."')"; mysql_query($qry); echo mysql_error(); } ?> <META HTTP-EQUIV="refresh" content="0;URL=vendor_add_product.php?ven_name=<? echo $v_name; ?>"> <? } else { if(isset($_POST['submit'])) { $str="INSERT INTO aa_vendor1(id,ven_name,category,landline,mobile,email,address,city,state,country,pin,cheque,cash,dd,banktransfer,chq_favr,dd_favr,dd_pay,website) VALUES ('','".$_POST['ven_name']."','".$_POST['category']."','".$_POST['landline']."','".$_POST['mobile']."','".$_POST['email']."','".$_POST['address']."','".$_POST['city']."','".$_POST['state']."','".$_POST['country']."','".$_POST['pin']."','".$_POST['cheque']."','".$_POST['cash']."','".$_POST['dd']."','".$_POST['banktransfer']."','".$_POST['payment_to_chq']."','".$_POST['payment_to_dd']."','".$_POST['payable_at']."','".$_POST['website']."')"; mysql_query($str); echo mysql_error(); $desg = $_POST['desg']; $user = $_POST['user']; $contact = $_POST['contact']; $emailid = $_POST['emailid']; $dept = $_POST['dept']; $count11 = count($desg); for($i=0 ; $i < count($desg); $i++) { $qry = "INSERT INTO contacts (`id`,`ven_name`,`desg`,`namee`,`contact`,`emailid`,dept) VALUES ('','".$_POST['ven_name']."','".$desg[$i]."','".$user[$i]."','".$contact[$i]."', '".$emailid[$i]."','".$dept[$i]."')"; mysql_query($qry); echo mysql_error(); } ?> <META HTTP-EQUIV="refresh" content="0;URL=vendor_add_product.php?ven_name=<? echo $v_name; ?>"> <? } } ?> </td> </tr> </table> <? } else { print "<p>Unauthorised Admin access - <a href=\"http://expense.webhop.org\">Click Here to Login</></p>"; } ?> </td> </tr> </table> <TABLE WIDTH="100%" CELLPADDING="0" CELLSPACING="1" BGCOLOR="<?php print "$HRColour"; ?>"> <TR> <TD></TD> </TR> </TABLE> <P ALIGN="CENTER" CLASS="copyright"><?php print "$Copyright"; ?></P> </body> </html> hii i struck ed with problem from last one weak. i want validations for two dropdown menu's... when user click on second dropdown menu by skipping first dropdown menu at that time alert box will come and it should say please select from upper menu.... please help me thanks this is the code but it's not working <HTML><HEAD> <TITLE>drop down validation</TITLE> <script type="text/javascript"> function validateForm(){ if(document.ItemList.Item.selectedIndex==0) { alert("Please select item from first list."); document.ItemList.Item.focus(); return false; } return true; } </SCRIPT> </HEAD> <BODY> Please choose an item from the drop down menu: <form name="ItemList" method="post" action="asp.html" onsubmit="validateForm()"> <table width="100%" border="0"> <tr> <td width="135">Choose a username: </td> <td> <select name="Item"> <option value selected> SELECT </option> <option value>Apples</option> <option value>Oranges</option> </select> <table width="100%" border="0"> <tr> <td width="135">Choose a username: </td> <td> <select name="Item" onchange="validateForm()"> <option value selected> SELECT </option> <option value>Apples</option> <option value>Oranges</option> </select> <input type="submit" name="Submit" value="Submit"> </td></tr></table></form> </BODY> </HTML> I would like to start off by saying I know there isn't a sure fire, 100% way to tell if javascript is enabled on a users browser. Because of this, it's a good idea to check form input using a php (or another server-side language) function. Now, let's say the user DOES have javascript enabled. I would like to check that same form input with a javascript function, instead of a php function. How would I be able to do that? If both php and javascript functions are in the same script, how does the browser know which one to run and how can I make it run the javascript function if the user has javascript enabled? I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> So if both validations work seperatley (if I just put radio buttons validation in the function without the spinner validation then radio buttons validation works and same vise versa), how come when I put both validations in the function, the top validation which is the radio validation works but the bottom validation which is the spinner validation does not display a message when it is suppose to? Code is below: Code: <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>Create a Session</title> <script type="text/javascript"> function validation() { var errMsgO = document.getElementById("radioAlert"); var btnRadioO = document.getElementsByName("sessionNo"); var isbtnRadioChecked = false; var errQuesMsgO = document.getElementById("numberAlert"); var questionNumberO = document.getElementsByName("txtQuestion"); for(i=0; i < btnRadioO.length; i++){ if(btnRadioO[i].checked){ isbtnRadioChecked = true; } } if(!isbtnRadioChecked) { errMsgO.innerHTML = "Please Select the Number of Sessions you Require"; } else { errMsgO.innerHTML = ""; } return false; if(questionNumberO[0].value == 0){ errQuesMsgO.innerHTML = "Please Set the Number of Questions"; } else { errQuesMsgO.innerHTML = ""; } return false; } </script> </head> <body> <form action="create_session.php" method="post" name="sessionform"> <table> <tr> <th>2: Number of Sessions :</th> <td class="sessionNo"><input type="radio" name="sessionNo" value="1" />1</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="2" />2</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="3" />3</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="4" />4</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="5" />5</td> </tr> </table> <div id="radioAlert"></div> <table> <tr> <th>Number of Questions:</th> <td class="spinner"><textarea class="spinnerQuestion" name="txtQuestion" id="txtQuestion" cols="2" rows="1"></textarea></td> <td><button class="scrollBtn" id="btnQuestionUp"><img src="Images/black_uppointing_triangle.png" alt="Increase" /></button> <button class="scrollBtn" id="btnQuestionDown"><img src="Images/black_downpointing_triangle.png" alt="Decrease" /></button></td> </tr> </table> <div id="numberAlert"></div> <p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="validation()" /></p> <!-- Prepare Questions here--> </form> </body> Hi guys, I need some help here.. I have created a simple JS and HTML NAME form validation and checked box as shown (If anyone can help me about the check box a better and easy way to code would be great). I would like to use the functions that I have created - can anyone tell me HOW I can use them please? I tried to use like this.. Code: var name = document.getElementById('name').value; if(name(!notEmpty && !isAlphabet)) { error_mesg += "\nPlease enter your Name"; error_num++; } ..but it does not work...anyone can give me some idea? Code: .. .. <script type='text/javascript'> function formValidation(){ var error_mesg = "Following error found\n"; var error_num = 0; var name = document.getElementById('name').value; if(name==""){ error_mesg += "\nPlease enter your Name"; error_num++; } var terms = !document.getElementById('terms').checked; //Can anyone tell me what is the function of "checked" here for? if (terms){ error_mesg += "\nPlease check the terms and conditions"; error_num++; } if(error_num>0){ alert(error_mesg); elem.focus(); return false; }else{ //submit form return true; } } function notEmpty(elem, error_mesg){ if(elem.value.length == 0){ alert(error_mesg); elem.focus(); // set the focus to this input return false; } return true; } function isAlphabet(elem, error_mesg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(error_mesg); elem.focus(); return false; } } .. .. [HTML FORM] .. <form name="form" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onsubmit="return formValidation()"> <tr align="left" valign="top> <td width="20%">NAME:<font color="#CE0000" >*</font></td> <td width="80%"><input name="name" type="text" id="name" size="30" /></td> </tr> <tr><td><input type=checkbox name=terms value='yes'>I agree to terms and conditions </td></tr> .. .. <input type="hidden" name="action" value="register"/> <input name="submit" type="submit" value="Proceed" /> <?php session_start(); include_once "../c-library/errorcheck.inc.php"; function viewForm($input,$errors){ //$array[] = $var; $num_days= array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21 ","22","23","24","25","26","27","28","29","30","31"); $num_months = array(1=>"Jan",2=>"Feb",3=>"Mar",4=>"Apr",5=>"May",6=>"Jun", 7=>"Jul",8=>"Aug",9=>"Sept",10=>"Oct",11=>"Nov",12=>"Dec" ); $gender = array("Male","Female"); ?> <!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>Register</title> <script src="reload_vals.js" type="text/javascript"></script> <style media="all"> table{ table-layout:auto; width:auto;} th{ text-align:right;} td #err{ color:#FF0000; font-weight:bold;} </style> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" > <h3><font face="Georgia" color="#000066" size="+2">Registeration</font></h3> <?php if (count($errors) > 0): echo "<p style='color:#ff0000'>*The following errors ocurred:</p>"; endif; ?> <table width="" border="1"> <tr> <th scope="row">Firstname:</th> <td><input name="fname" type="text" id="fname" size="28" value="<?php echo htmlentities($input['fname'])?>" /></td> <td id="err"><?php echo $errors['fname'] ?></td> </tr> <tr> <th scope="row">Lastname:</th> <td><input name="lname" type="text" id="lname" size="28" value="<?php echo htmlentities($input['lname'])?>" /></td> <td><?php echo $errors['lname'] ?></td> </tr> <tr> <th scope="row">Date of Birth:</th> <td> <select name="days" size="1" id ="days" > <option value='-------'>--Day--</option> <?php /* day starts here*/ (array)$num_days; foreach ($num_days as $day): printf("<option value=\"%s\" %s>%s</option>",$day,($days==$day ? "selected='selected'" : ""), $day); endforeach; /* day ends and months start here*/ ?> </select> <select name="" size="1" id =""> <?php /* month ends and starts here*/ ?> </select><select name="" size="1" id =""> <?php ?> </select> <br /><small style="text-align:center; color:#006600;">dd-mm-yyy</small> </td> <td><?php echo $errors['date'] ?></td> </tr> <tr> <th scope="row">Sex:</th> <td> <select name="" size="1" id =""> <?php /* Sex selection starts here;*/ /* Sex selection starts here; */ ?> </select></td> <td><?php echo $errors['sex'] ?></td> </tr> <tr> <th scope="row">Email:</th> <td><input name="email" type="text" id="email" size="28" value="<?php echo htmlentities($input['email']) ?>"/></td> <td><?php echo $errors['email'] ?></td> </tr> <tr> <th scope="row">Password:</th> <td><input name="password" type="password" id="password" size="28" value="<?php echo htmlentities($input['password']) ?>"/></td> <td><?php echo $errors['password'] ?></td> </tr> <tr> <th scope="row">Comfirm Password:</th> <td><input name="password2" type="password" id="password2" size="28" value="<?php echo htmlentities($input['password2']) ?>"/></td> <td> </td> </tr> <tr> <th scope="row"> </th> <td> </td> <td> </td> </tr> <tr> <th scope="row">I agree:</th> <td><input name="agree" type="checkbox" id="agree" value="<?php echo $input['agree']='agree'?>" /></td> <td><?php echo $errors['agree'] ?></td> </tr> <tr> <th scope="row"><input name="action" type="hidden" id="submitted" value="TRUE" /></th> <td><input name="add_newuser" type="submit" id="submit" value="I accept, Register me" /></td> <td> </td> </tr> </table> </form> </body> </html> <?php } function register_user($input){ include "../c-library/database.inc.php"; // $input = $_REQUEST; $input['fname'] = mysql_escape_string(stripslashes($input['fname'])); $input['lname'] = mysql_real_escape_string(stripslashes($input['lname'])); //$input['day'] $input['date'] = $input['year'].''.$input['month'].''.$input['day']; $input['sex'] = $input['sex']; $input['email'] = mysql_real_escape_string($input['email']); $input['password'] = mysql_real_escape_string(md5($input['password'])); $input['uid'] = uniqid(rand(16,32),true); $qr ="insert into users(id,Firstname,Lastname,Date_of_Birth,Sex,Email,Password,Userid) values('null','$input[fname]','$input[lname]','$input[date]','$input[sex]','$input[email]','$input[password]','$input[uid]')"; $results = mysql_query($qr,$sdayb); return $results; mysql_close($sdayb); echo "thanks";//header("Location: thankyou.html"); } /*ex. user enters - 19/11/1980 $var = explode('/', '19/11/1980'); $sdayd = $var[0]; $mm = $var[1]; $yyyy = $var[2]; */ if(isset($_POST['add_newuser'])): $inputs = $_POST; $setErrors = array(); if(!check_formerr($inputs, $setErrors)): viewForm($inputs, $setErrors); else: register_user($inputs); endif; else: viewForm(null, null); endif; ?> when user clicks submit first it should check to see if a name from the dropdown has been selected then it should check to make sure all radio buttons were selected. code to check if a name was selected in the drop down. Code: <script type="text/javascript"> window.onload=function(){ document.forms[0].onsubmit=function(){ return formValid(this); } } function formValid(formObj){ var sel=formObj.getElementsByTagName('select'); var len=sel.length; var msg = "You forgot to select your name" var flg=false; for(var i=0;i<len;i++){ if(sel[i].selectedIndex==0){ msg; flg=true; } } if(flg){ alert(msg); return false; }else{ return true; } } </script> <br><br> <html> code that checks to see if all radio buttons were selected. Code: function validateTest() { var focus_me = null; var msg = ""; var form = document.forms[0]; for ( var game = 1; game <= 999999; ++game ) { var rbg = form["game" + game]; if ( rbg == null ) break; // no more games if ( ! rbg[0].checked && ! rbg[1].checked ) { msg += rbg[0].value + " vs. " + rbg[1].value + "\n"; focus_me = focus_me || rbg[0]; } } if (msg != "") { var prefix = "\n WARNING: The following Games(s) were not selected:\n\n"; var suffix = "\nClick OK and select all games before clicking submit.\n\n"; alert(prefix + msg + suffix); if (focus_me) focus_me.focus(); return false; } else{ return true; } } Code: center> <INPUT TYPE=SUBMIT VALUE="submit" onClick="Validate(this.form, 'game1')"> </FORM> how can i add these two functions together so it validates both? Ill tell you the story and then simplify it ok i have a computer site that you can build your own computer and whatnot but i just recently thought about how not everyone knows which parts are needed in a computer... my first design of the site had the name of the part in the select box as default but now i removed the name of each part outside of the select boxes but the problem now is i need some type of onLoad event to happen when the page loads to call out the functions that are associated with the selected boxes...... i have 2 fuctions in an external js file Code: function swapImage(sel,id){ document.getElementById(id).src = sel.value.split('#')[1]; } and Code: function Calculate(){ var a = parseFloat(document.comp.caseselect.value.split('#')[0]); var b = parseFloat(document.comp.powersupply.value.split('#')[0]); var sum = a+b; document.getElementById("total").innerHTML = '$'+sum; } when someone selects an item it adds the price to the price of other selected items and shows the total price elsewhere on the page... also shows a picture of the selected item on the page.. im just going to show the first select box to show you how all my select boxes are written Code: <p align="left">CASE</p> <center> <select name="caseselect" style="width:625px" onchange="Calculate(); swapImage(this,'caseimg');"> <option value="50#COOLER MASTER Elite 310red.jpg" selected="1">COOLER MASTER Elite 310 Red ($50.00)</option> <option value="50#COOLER MASTER Elite 310blue.jpg">COOLER MASTER Elite 310 Blue ($50.00)</option> <option value="50#COOLER MASTER Elite 310orange.jpg">COOLER MASTER Elite 310 Orange ($50.00)</option> <option value="50#COOLER MASTER Elite 310silver.jpg">COOLER MASTER Elite 310 Silver ($50.00)</option> </select> *not that it matters but yes there is an ending center in my html but its at the end of the group the image is sent here Code: <img src="start.jpg" id="caseimg" /> and the price is sent here Code: <span style="color:black; font-size:20pt">YOUR PRICE UPDATE</span><br /> <span id="total" style="color:white; font-size:32pt">$0 Nothing Selected</span> code works perfectly fine ONCE YOU SELECT SOMETHING ELSE but i need it to work when the page loads I am trying to do a custom add to cart to use with paypal and need to utilize javascript to achieve inserting some code or a weight value per the paypal forms' options choice. Here is my dilemma, All of my items have multiple weights, for instance the below example called Aqua Max 100 comes in .5lbs, 1.5lbs., 10lbs., 20lbs., and 50lbs. Paypal allows you to enter weight but it's one weight per item and I would have to create 5 Paypal buttons just for this one item to calculate the different weights per zip code. I need help making javascript insert the following code within the paypal forms' code upon option select before clicking submit? <input type="hidden" name="weight" value=".5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="1.5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="10 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="20 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="50 <input type="hidden" name="weight_unit" value="lbs"> The code I came up with is wrong as I'm getting an error but I was originally trying to make it enter a weight using a hidden fillable number and without any real javascript training, just alot of googling but I think I'm pretty close. Please take a look at the code I've came up with so far and maybe point me in the correct direction: <html> <body> <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="business" value="test@test.com"> <input type="hidden" name="currency_code" value="USD"> <input type='hidden'text' name='amt' id='amt' value="0.00"/> <table> <tr> <td> <input type="text" name="on0" value="Aqua Max 100">Aqua Max 100</td></tr> <tr><td> <select name="os0" onChange="getamt()"> <option value="select">Please Select</option> <option value="1/2 lb.">1/2 lb. $3.99 USD</option> <option value="1 - 1/2 lbs">1 - 1/2 lbs $7.59 USD</option> <option value="10 lbs.">10 lbs. $25.80 USD</option> <option value="20 lbs.">20 lbs. $42.75 USD</option> <option value="50 lbs.">50 lbs. $86.20 USD</option> </select></td></tr> </table> <script type="text/javascript"> function getamt() { var sh=0; var choice = document.getElementById("os0").selectedIndex; if (choice == 0) { sh=0; } if (choice == 1) { sh=.5; } if (choice == 2) { sh=1.5; } if (choice == 3) { sh=10; } if (choice == 4) { sh=20 } if (choice == 5) { sh=50.00; } document.getElementById("on0").value=sh; } </script> <input type="image" src="https://images.paypal.com/images/sc-but-03.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> </body> </html> How can I add a form field value to a url. I tried the below but it no work. Code: href="index2.php?q=4&id=+document.theForm.lists.value+&picklist" Hi there, I have a html form, and I need it so that when a user clicks a button, it adds a field into the form. I also need it to write <td></td> around the new field, and I need it to write this in a specific part row of a table. How would I go about doing this? I've tried searching for the past two hours, but no luck. Many thanks, I appreciate it, Jason Is there a way to give an input or textarea field the focus and set the focus to begin right at the end of the current text in the field?
Hi! I use the :: Form field Progress Bar from DynamicDrive: Form field Progress Bar Now I trided to change the text when the textarea is full "Limit:100%" to "Your max. characters is reached" I trided it but with no luck. This is the main code.. Code: <script type="text/JavaScript"> function textCounter1(field,counter,maxlimit,linecounter) { // text width// var fieldWidth = 137; var charcnt = field.value.length; // trim the extra text if (charcnt > maxlimit) { field.value = field.value.substring(0, maxlimit); } else { // progress bar percentage var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ; document.getElementById(counter).style.width = parseInt((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" // color correction on style from CCFFF -> CC0000 setcolor(document.getElementById(counter),percentage,"background-color"); } } function setcolor(obj,percentage,prop){ obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)"; } </script> This is the place where the text is set. Code: ((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" Help would be highly appreciated ! greetings Jardin I have a form which has various fields which are arrays (so the name of a field may be myField[]). The reason for this is that the form has add buttons to add another field or fields for the purpose of entering another email address, etc., to send invitations and do other things. The problem that I am running into is how to access the individual fields in an array of fields inside javascript to do form validation. So if I have an email address field name emailAddress[], and using the add button, the user of my site adds 3 other copies of the emailAddress[] field, I want to then do form validation onSubmit to ensure those email address are valid using standard procedures. However, inside the javascript code, how do I access the individual fields that make up emailAddress[]? I just cannot find anywhere online the proper way to get at these values. If anyone can help me, I would greatly appreciate it. Happy Holidays I need to learn how to clear form fields when a user clicks on them. Here is the site in question: http://www.yourvancouvermortgagebroker.ca/apply They used to work, but then I changed the field value and now it doesn't work on some of the fields (whichever ones I changed). Here is a link to the .js file: http://www.yourvancouvermortgagebroker.ca/js/apply.js function checkValidFormInput() { if (document.getElementsByName('customerName').value != '') { document.getElementById('customerNameImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerNameImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } if (document.getElementsByName('customerEmail').length > 0) { document.getElementById('customerEmailImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerEmailImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } } |