I have a sign up form where I have taken some basic details of the customer and a Submit button.
I have validate all the fields using ajax but confirm password field using javascript. When I write code only using Ajax and not validating Confirm password field it is running perfectly but the problem is when I am validation it using JS submit button is not getting enable.
Sign up form:
<html>
<head>
<title> Registration Form </title>
<script language="javascript">
var flag = false;
function validate(element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new Activexobject("Microsoft.XMLHTTP");
}
var myField = element;
xmlhttp.open('GET', 'validate.php?' + myField.id + "=" + myField.value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
//alert("Hello");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var response = xmlhttp.responseText.split("||");
//alert("H2");
}
var divname = "err" + myField.id.substring(3);
var mydiv = document.getElementById(divname);
if (!eval(response[0]))
{
//alert("Fail");
//alert("Value: "+response);
mydiv.innerHTML = response[1];
myField.valid = false;
}
else
{
//alert("Success");
myField.valid = true;
mydiv.innerHTML = "";
}
var btn = document.getElementById("btnSubmit");
btn.disabled = !isValidForm();
}
}
;
function password()
{
var pass = document.getElementById("txtpswd").value;
var Confirm_pass = document.getElementById("txtConfirmpassword").value;
alert("Pass " + pass);
alert("Confirm: " + Confirm_pass);
if (pass == Confirm_pass)
{
flag = true;
alert("True");
document.getElementById("errConfirmpassword").innerHTML = "";
}
else
{
alert("False");
flag = false;
document.getElementById("errConfirmpassword").innerHTML = "Password does not Match";
}
}
;
function isValidForm()
{
var f1 = document.getElementById("txtfname");
var f2 = document.getElementById("txtlname");
var f3 = document.getElementById("txtaddress");
var f4 = document.getElementById("txtzip");
var f5 = document.getElementById("txtnumber");
var f6 = document.getElementById("txtmail");
var f7 = document.getElementById("txtpswd");
var f8 = document.getElementById("txtConfirmpassword");
return(f1.valid && f2.valid && f3.valid && f4.valid && f5.valid && f6.valid && f7.valid && f8.valid);
}
;
</script>
</head>
<body>
<center>
<h1><font color="red"> New User Registration Form </font></h1>
<form name="SignUpForm" method="POST" action="function_customer.php?val=insert">
<table>
<tr>
<td id=q> <font face="Century Schoolbook"> First Name :</font></td> <br>
<td> <input type=text name=txtfname id="txtfname" placeholder=First_name onchange="validate(this);" valid=false> </td>
<td><div id="errfname"/></td>
</tr>
<tr>
<td id=q> Last Name :</td>
<td> <input type=text name=txtlname id="txtlname" placeholder=Last_Name onchange="validate(this);" valid=false> </td>
<td><div id="errlname"/></td>
</tr>
<tr>
<td id=q>Address : </td><br>
<td> <textarea rows=5 cols=20 name="txtaddress" id="txtaddress" onchange="validate(this);" valid=false>
</textarea>
</td>
<td><div id="erraddress"/></td>
</tr>
<tr>
<td id=q> Contact no : </td>
<td> <input type=text name="txtnumber" id="txtnumber" onchange="validate(this);" valid=false> </td>
<td><div id="errnumber"/></td>
</tr>
<tr>
<td id=q> Gender </td>
<td> <select name="txtcity" id="gender">
<option value="Male"> Male </option>
<option value="Female"> Female </option>
</select>
</td>
</tr>
<tr>
<td id=q> City </td>
<td>
<select name="txtcity" id="txtcity">
<option> City </option>
<option value="Vadodara"> Vadodara </option>
<option value="Ahmedabad"> Ahmedabad </option>
<option value="Surat"> Surat </option>
<option value="Rajkot"> Rajkot </option>
<option value="Bhavnagar">Bhavnagar</option>
<option value="Jamnagar">Jamnagar</option>
<option value="Nadidad">Nadidad</option>
<option value="Morvi">Morvi</option>
<option value="Gandhidham">Gandhidham</option>
<option value="Adipur">Adipur</option>
<option value="Anand">Anand</option>
<option value="Baruch">Baruch</option>
<option value="Godhra">Godhra</option>
<option value="Veraval">Veraval</option>
<option value="Navsari">Navsari</option>
</select>
</td>
</tr>
<tr>
<td id=q> ZIP : </td>
<td> <input type=text name=txtzip id="txtzip" onchange="validate(this);" valid=false> </td>
<td><div id="errzip"/></td>
</tr>
<tr>
<td id=q> Email Id : </td>
<td> <input type="email" name=txtmail placeholder=someone#exe.com id="txtmail" onchange="validate(this);" valid=false> </td>
<td><div id="errmail"/></td>
</tr>
<tr>
<td id=q> New Password : </td>
<td> <input type="password" name="txtpswd" id="txtpswd" onchange="validate(this);" valid=false>
</td>
<td><div id="errpswd"/></td>
</tr>
<tr>
<td id=q>Confirm Password : </td><td><input type="password" name=txtConfirmpassword id="txtConfirmpassword" onchange="password();" valid=false>
</td>
<td><div id="errConfirmpassword"/></td>
</tr>
<tr>
<td></td><td><input type=reset name=reset value=Reset>
</td>
</tr>
<tr>
</tr>
</table>
</form>
<br>
<br>
<br>
<br><br>
</center>
</body>
</html>
What should I do to validate all the fields and enabling the Submit Button?
First of all I suggest you read up on the latest HTML elements and use CSS for centering or styling your elements and avoid usage of obsolete elements like <font> and <center>.
Having said that, the issue in your code is that you're not calling validate() to check if the form is valid after password & confirm password fields match, so change your password() like below.
function password(){
var btn = document.getElementById("btnSubmit");
var pass = document.getElementById("txtpswd").value;
var confirm_pass = document.getElementById("txtConfirmpassword").value;
var pwdErrorElement = document.getElementById("errConfirmpassword");
if (pass === confirm_pass){
flag = true;
pwdErrorElement.innerHTML = "";
btn.disabled = !isValidForm();
}else{
flag = false;
pwdErrorElement.innerHTML = "Password does not Match";
btn.disabled = true;
}
}
Also I suggest you to make use of value property on each field to do the validations on client side rather than making a server call for every field change. You can use field values for validations by changing the last statement in your isValidForm() like below.
function isValidForm(){
// get all the field references
return(f1.value && f2.value && f3.value && f4.value
&& f5.value && f6.value && f7.value && f8.value);
}
Once you're done with the JS validations, you can enable the submit button and do validations for all fields at once on your server side on form submit. I mean that's the very purpose of doing client side validations using JS. You don't want to ask for feedback (valid or not) for every field change.
Here's a working Pen with all the above changes.
Related
How can i add prevent-default() with focus-out() in my form. I face problem when i click the reset button in my form. It show the last focusing input field error message when i click the reset button. Here my code bellow:
$(document).ready(function(){
//error message section:
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
//username validation area:
function checkUsername(){
var name = $("#username").val();
var usernameLength = $("#username").val().length;
if(!name.replace(/\s/g, '').length){
$("#username_error_msg").html("<span class='errorMessage'>Username shouldn't be empty..!</span>").slideDown(500);
}else if(usernameLength < 5 || usernameLength > 20){
$("#username_error_msg").html("<span class='errorMessage'>Username should be between 5-20 characters..!</span>").slideDown(500);
}else{
$("#username_error_msg").slideUp(500);
return true;
}
}
//Gender selection check:
function checkGenderSelection(){
var genderCategory = $('select[name=Gender]').val();
if(genderCategory == 'Select'){
$("#gender_Select_error_msg").html("<span class='errorMessage'>Please select your gender..!</span>").slideDown(500);
}else if((genderCategory == 'Male') || (genderCategory == 'Female')){
$("#gender_Select_error_msg").slideUp(500);
return true;
}
}
//job category check: radiobutton
function checkJobCategorySelection(){
var jobCategory = $('input[name=jobCategory]:checked');
if(jobCategory.length == 0){
$("#jobCategory_error_msg").html("<span class='errorMessage'>No Category Selected..!</span>").slideDown(500);
}else{
$("#jobCategory_error_msg").slideUp(500);
return true;
//By this way we can collect the value from radio button for further action//
//console.log("Selected Item: " + jobCategory.val());
}
}
//programming Experience check: checkbox
function programmingExperienceCheck(){
var experienceList = $('input:checkbox[name=language]:checked');
if(experienceList.length == 0){
$("#experience_sector_error_msg").html("<span class='errorMessage'>No Sector Selected..!</span>").slideDown(500);
}else{
$("#experience_sector_error_msg").slideUp(500);
return true;
}
}
//password validation area:
function checkPassword(){
var pass = $("#password").val();
var passwordLength = $("#password").val().length;
if(!pass.replace(/\s/g, '').length){
$("#password_error_msg").html("<span class='errorMessage'>Please type your password..!</span>").slideDown(500);
}else if(passwordLength < 8){
$("#password_error_msg").html("<span class='errorMessage'>Password should be minimum 8 characters..!<span class='errorMessage'>").slideDown(500);
}else{
$("#password_error_msg").slideUp(500);
return true;
}
}
//retype password validation area:
function checkRetypePassword(){
var pass = $("#password").val();
var retypePass = $("#retype_password").val();
if(!retypePass.replace(/\s/g, '').length){
$("#retype_password_error_msg").html("<span class='errorMessage'>Please give your password again..!</span>").slideDown(500);
}
else if(pass !== retypePass){
$("#retype_password_error_msg").html("<span class='errorMessage'>Password don't match..!</span>").slideDown(500);
}else{
$("#retype_password_error_msg").slideUp(500);
return true;
}
}
//email validation area:
function checkEmail(){
var regularExp = new RegExp(/([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})/);
if(!$("#email").val().replace(/\s/g, '').length){
$("#email_error_msg").html("<span class='errorMessage'>Please give your email id..!</span>").slideDown(500);
}
else if(regularExp.test($("#email").val())){
$("#email_error_msg").slideUp(500);
return true;
}else{
$("#email_error_msg").html("<span class='errorMessage'>Invalid Email..!</span>").slideDown(500);
}
}
//phone number validation area:
function checkPhoneNumber(){
var phone_number = $("#phoneNo").val();
var regularExp = new RegExp(/^(?:\+?88)?01[15-9]\d{8}$/);
if(!phone_number.replace(/\s/g, '').length){
$("#phone_no_error_msg").html("<span class='errorMessage'>Please enter a phone number..!</span>").slideDown(500);
}else if(regularExp.test($("#phoneNo").val())){
$("#phone_no_error_msg").slideUp(500);
return true;
}else{
$("#phone_no_error_msg").html("<span class='errorMessage'>Invalid phone number..!</span>").slideDown(500);
}
}
//short notes validation area:
function checkShortNotes(){
var shortNotes = $("#short_note").val();
var shortNotesLength = $("#short_note").val().length;
if(!shortNotes.replace(/\s/g, '').length){
$("#short_note_error_msg").html("<span class='errorMessage'>You have to write something about you..!</span>").slideDown(500);
}else if(shortNotesLength < 10){
$("#short_note_error_msg").html("<span class='errorMessage'>Your notes is too short..!</span>").slideDown(500);
}else{
$("#short_note_error_msg").slideUp(500);
return true;
}
}
//username focus action:
$("#username").focusout(function(){
if($('input[type=reset]').data('clicked',false)){
checkUsername();
}
});
//gender focus action:
$("#gender").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkGenderSelection();
}
});
//password focus action:
$("#password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPassword();
}
});
//retypePassword focus action:
$("#retype_password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkRetypePassword();
}
});
//email focus action:
$("#email").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkEmail();
}
});
//phone number focus action:
$("#phoneNo").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPhoneNumber();
}
});
//shortNotes focus action:
$("#short_note").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkShortNotes();
}
});
//form submit action:
$("#myForm").submit(function(){
if(checkUsername() && checkGenderSelection() && checkJobCategorySelection() && programmingExperienceCheck() && checkPassword() && checkRetypePassword() && checkEmail() && checkPhoneNumber() && checkShortNotes()){
return true;
}
else{
return false;
}
});
});
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
});
.errorMessage{background-color: darkcyan;color:white; border-radius:2px;font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="msg.php" method="post">
<table>
<tr>
<td>Username: </td>
<td><input type="text" id="username"></td>
<td><span id="username_error_msg"></span></td>
</tr>
<tr>
<td>Select Your Gender: </td>
<td>
<select name="Gender" id="gender">
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td><span id="gender_Select_error_msg"></span></td>
</tr>
<tr>
<td>Select Job Category: </td>
<td>
<input type="radio" name="jobCategory" value="Part Time"/> Part Time
<input type="radio" name="jobCategory" value="Full Time"/> Full Time
<input type="radio" name="jobCategory" value="Intern"/> Intern
</td>
<td><span id="jobCategory_error_msg"></span></td>
</tr>
<tr>
<td>Select Experience Sector:</td>
<td>
<input type="checkbox" name="language"/> Javascript
<input type="checkbox" name="language"/> PHP
<input type="checkbox" name="language"/> Jquery
</td>
<td><span id="experience_sector_error_msg"></span></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password"></td>
<td><span id="password_error_msg"></span></td>
</tr>
<tr>
<td>Retype Password: </td>
<td><input type="password" id="retype_password"></td>
<td><span id="retype_password_error_msg"></span></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email"></td>
<td><span id="email_error_msg"></span></td>
</tr>
<tr>
<td>Phone No: </td>
<td><input type="text" id="phoneNo"></td>
<td><span id="phone_no_error_msg"></span></td>
</tr>
<tr>
<td>Short Note About You: </td>
<td><textarea id="short_note" cols="22" rows="5"></textarea></td>
<td><span id="short_note_error_msg"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
<input type="reset" value="Refresh"/>
</td>
<td></td>
</tr>
</table>
</form>
});
How can i stop to seeing any focus-out() action when i click reset button????
When you reset the form, you are hiding all the error messages. Then focus on the first element - username.
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
$('#username').focus();
});
Blur comes before click so you are setting the .html of the error, then the click comes and you hide it but because you use .slide jQuery will then set it visible again as it's sliding in.
The simplest way would be to set the html of the error to an empty string, jQuery can then slide in an empty string:
function removeErrors(){
$("#username_error_msg").html("");
$("#gender_Select_error_msg").html("");
$("#jobCategory_error_msg").html("");
$("#experience_sector_error_msg").html("");
$("#password_error_msg").html("");
$("#retype_password_error_msg").html("");
$("#email_error_msg").html("");
$("#phone_no_error_msg").html("");
$("#short_note_error_msg").html("");
}
//refresh button action:
$('input[type=reset]').click(function(){
removeErrors();
});
I Cannot get the javascript to work! I need the Password and Re-Type Password fields, validate that both have values and that the user has entered the same password in both fields (i.e. password match) validate the password field must be more than 8 characters.I dont want to use the alert function instead, highlight the uncompleted fields with red background and a text message next to each uncompleted field (in red color) with the error message.
I have spent 3 days doing this!! any help appreciated.`
function validate() {
var fn =
document.getElementById("FName");
if (fn.value == "") {
{
document.getElementById("FName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var sn =
document.getElementById("SName");
if (sn.value == "") {
document.getElementById("SName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var un =
document.getElementById("UName");
if (un.value == "") {
document.getElementById("UName").style.borderColor = "red";
return false;
}
return true;
}
function checkPass() {
var pass = document.getElementById('pass');
var c_pass = document.getElementById(' c_pass')
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value == c_pass.value) {
c_pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
c_pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
return true;
}
}
<body>
<form action="Linkpage.html" id="myForm" method="post" name="myForm" onsubmit="return(validate())">
</form>
<br>
<table>
<tr>
<td align="center" colspan="2"><span style="font-size:50px; color:blue;">Registration form</span>
</td>
</tr>
<tr>
<td align="center" colspan="2">Welcome to our website
<br>please fill in <span style=" color:red;">all</span>
<b><ins>fields</ins></b>
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input autofocus="" id="FName" placeholder="Enter First name " type="text">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input id="SName" placeholder="Enter Last name " type="text">
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input id="UName" placeholder="Enter username " type "text">
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input id="Age" placeholder="Enter age" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="pass" placeholder="Enter password " type="password">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm password" id="c_pass" placeholder="Re-type your password " type="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
</td>
</tr>
<tr>
<td rowspan="2">Gender</td>
<td>
<input name="mGender" type="radio" value="Male">Male</td>
</tr>
<tr>
<td>
<input name="fGender" type="radio" value="Female">Female</td>
</tr>
<tr>
<td>Available</td>
<td>
<input id="checkbox" type="checkbox">
</td>
</tr>
<tr>
<td>Course</td>
<td>
<select>
<option value="Mobile App">
Mobile App
</option>
<option value="Cloud">
Cloud
</option>
<option value="Software Development">
Software Development
</option>
</select>
</td>
</tr>
<tr>
<td class="Comments">Comments</td>
<td>
<br>
<textarea cols="30" name="Comments" placeholder="Type your comments here." rows="6"></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4" align="center">
<input name="submit" onclick="return validate()" type="submit" value="Register" align="center" />
</td>
</tr>
</table>
</body>
A couple of things here...
Get rid of the table, tr and td. You open a form and then you close it. Add all of your input fields in the form.
Then don't add three functions all called validate. Which one do you suppose is going to be called?
Rather change them to
function validateFname()
function validateSname()
function validateUname()
then
Use === and !=== instead of == and !=.
I think when you start clearing up your JavaScript and your HTML, things will start to make more sense.
Did you try to debug your code using Chrome's debugger or similar?
Each time you write the validate() function, you're overwriting the previous instance of it.
I recommend instead of using the same function name 3 times, write 2 different functions - matches() and required(), each with a different purpose.
matches(field1, field2){
return field1 == field2;
}
required(field){
return field != false;
}
Then you can pass into those functions the various fields you're validating.
There are a lot of bugs in your code and this is normal as a beginner its great to see you trying. So what I have done is took a look at your javascript. I am not going to re-write you whole script but I have commented out the part you should take a look at and try and comment one part at a time to see where you problem is. But I did get your match password working for you by commenting out your other stuff. Just try this for now. Then remove comments line by line until it stops working again. This will tell you how to find the other error's in your script.
<script>
function checkPass(){
var passValue = document.getElementById('pass').value;
var c_passValue = document.getElementById('c_pass').value;
var c_passID = document.getElementById('c_pass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(passValue == c_passValue) {
c_passID.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!";
} else {
c_passID.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
</script>
Okay so the issue was that you were attempting to change the color of the value of the c_pass and not the id itself. I renamed your variables to help you understand why it was breaking. Again this is only for the checkPass function. If you comment out all the other stuff and just use this script for now this will help you isolate the checkPass function and see that it works. I hope this helps.
I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}
I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net
Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)
I would like to run a for loop that will insert a word in a text box from a table; then insert a new word in a text box right after that.
However i only get one word when i click submit is there a way to do this without ajax?
function check()
{
var myrows = new Array();
myrows[0] = "row1";
myrows[1] = "row2";
var server =" ";
var root = " ";
for (var i=0;i<myrows.length;i++){
root = myrows[i]+ "rootname";
server = myrows[i]+ "servername";
var j = document.getElementById(root);
var y = document.getElementById(server);
document.getElementById('id_rootname').value=j.textContent;
document.getElementById('id_servername').value=y.textContent;
}
var x;
var r=confirm("Are you sure you?" );
if (r==true)
{
x="You pressed OK!";
}
else
{
Object.cancel;
}
}
</script>
<tr >
<td align="center"><input type="checkbox" class="selectedId"
onclick="resetSelectedAll(this);" id= "check" value="row1" name="row{{ forloop.counter }" ></td>
<td name = "root" id="row1rootname">appBOWSERtest033</td>
<td style="display:none;" name = "server" id="row1servername">Bowser</td>
<td name= "url" id="row1urls">21</td>
<td id="row1custs">3</td>
<td id="row1jvmms"> 1024</td>
<td id="row1x64">1</td>
<td id="row1currentplatform"> platform_11.3.111129.38873</td>
<td id="row1currentjdk"> jdk_1.6.0_26-b03</td>
<td id="row1currenttomcat">tomcat_6.0.32</td>
</tr>
<tr >
<td align="center"><input type="checkbox" class="selectedId"
onclick="resetSelectedAll(this);" id= "check" value="row2" name="row{{ forloop.counter }" ></td>
<td name = "root" id="row2rootname">appLUIGItest033</td>
<td style="display:none;" name = "server" id="row2servername">LUIGI</td>
<td name= "url" id="row2urls">12</td>
<td id="row2custs">3</td>
<td id="row2jvmms"> 1024</td>
<td id="row2x64">0</td>
<td id="row2currentplatform"> platform_12.1.120510.42747</td>
<td id="row2currentjdk"> jdk_1.6.0_31-b04</td>
<td id="row2currenttomcat">tomcat_7.0.27</td>
</tr>
<form action=" " id ="forms" name = "forms" >{% csrf_token %}
<table>
<tr><th><label for="id_servername">Servername:</label></th><td><input id="id_servername" maxlength="50" name="servername" type="text" value="LUIGI" /></td></tr>
<tr><th><label for="id_rootname">Rootname:</label></th><td><input id="id_rootname" maxlength="50" name="rootname" type="text" value="appLUIGItest033" /></td></tr>
<tr><th><label for="id_action">Action:</label></th><td><select id="id_action" name="action">
<option value="Restart" selected="selected">Restart</option>
<option value="Full_Dump">Full_Dump</option>
<option value="Redeploy">Redeploy</option>
<option value="Thread">Thread</option>
</select></td></tr>
<tr><th><label for="id_loginname">Loginname:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_loginname" maxlength="50" name="loginname" type="text" /></td></tr>
<tr><th><label for="id_choice">Choice:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_choice" name="choice" type="checkbox" /></td></tr>
</table>
<input name = "hello" type="submit" onclick="check()" value="Submit">
</form>
root = myrows[i]+ "rootname";
server = myrows[i]+ "servername";
var j = document.getElementById(root);
var y = document.getElementById(server);
instead of this try this one.
start var i = 1 in for loop.
var j= document.getElementById("row"+i+"rootname");
I'm no javascript expert and i'm currently trying to create a function for a form that has the same fields repeated depending on a number selected on a previous page.
There could be between 1 and 10 rows of the form fields with each having a radio button selection that will enable/disable each row.
At the moment i've written something but having trouble with concatenating form field names and variable names.
Is anyone able to point me in the right direction please.
Javascript:
var i = 1;
var iChildren = 2; //could be any number - depends what user selected.
function toggle(switchElement) {
for (i = 1; i = iChildren; i++) {
var frmSchoolSelected+i = document.getElementById('<%=c_' & i & '_selected.ClientID%>');
var frmSchoolAge+i = document.getElementById('<%=c_' & i & '_type.ClientID%>');
var frmSchoolType+i = document.getElementById('<%=c_' & i & '_type1.ClientID%>');
var frmSchoolAdditional+i = document.getElementById('<%=c_' & i & '_additional.ClientID%>');
if (switchElement.value == 'Yes') {
frmSchoolSelected+i.disabled = false;
frmSchoolAge+i.disabled = true;
frmSchoolType+i.disabled = true;
frmSchoolAdditional+i.disabled = true;
}
else {
frmSchoolSelected+i.disabled = true;
frmSchoolAge+i.disabled = false;
frmSchoolType+i.disabled = false;
frmSchoolAdditional+i.disabled = false;
}
}
}
Thanks for any help.
J.
EDITED
Example of generated form HTML.
<form method="post" action="schoolingform.aspx" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'Button1')" id="form1">
<table id="Table1" cellspacing="0" cellpadding="0" style="border-width:0px;border-collapse:collapse;">
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><span id="c_1_school_selected" onlick="javascript:toggle(this);">
<input id="c_1_school_selected_0" type="radio" name="c_1_school_selected" value="Yes" />
<label for="c_1_school_selected_0">Yes</label>
<input id="c_1_school_selected_1" type="radio" name="c_1_school_selected" value="No" />
<label for="c_1_school_selected_1">No</label>
</span></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Fred Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_1_selected" type="text" id="c_1_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_1_id" id="c_1_id" value="22" /></td>
<td><select name="c_1_type" id="c_1_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_1_type1" id="c_1_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_1_additional" rows="6" cols="30" id="c_1_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><span id="c_2_school_selected" onlick="javascript:toggle(this);">
<input id="c_2_school_selected_0" type="radio" name="c_2_school_selected" value="Yes" />
<label for="c_2_school_selected_0">Yes</label>
<input id="c_2_school_selected_1" type="radio" name="c_2_school_selected" value="No" />
<label for="c_2_school_selected_1">No</label>
</span></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Sara Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_2_selected" type="text" id="c_2_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_2_id" id="c_2_id" value="23" /></td>
<td><select name="c_2_type" id="c_2_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_2_type1" id="c_2_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_2_additional" rows="6" cols="30" id="c_2_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td align="right" colspan="5"></td>
</tr>
</table>
<input type="hidden" name="iChild" id="iChild" value="2" />
<input type="submit" name="Button1" value="Next" id="Button1" class="submitBtn" />
You are mixing .NET code and JavaScript code. Because .NET runs first, it will try to process the code as you have written it:
<%=c_' & i & '_selected.ClientID%>
and most likely generate an error message because that is invalid code.
A simpler solution might be to use a class name. Then with jQuery, you could condense all of your code into a single call:
$('.ClassName').toggle();
Illegal javascript syntax. You ARE mixing .net and JS
var frmSchoolSelected+i is not allowed.
Also your loop is assigning i instead of testing i (= versus ==)
try this
function toggle(switchElement) {
var clientId = '<%=c_1_selected.ClientID%>';
var isYes = switchElement.value == 'Yes';
for (var i=1; i==iChildren; i++) {
var frmSchoolSelected = document.getElementById(clientId.replace('_1_selected','_'+i+'_selected'));
var frmSchoolAge = document.getElementById(clientId.replace('_1_selected','_'+i+'_type'));
var frmSchoolType = document.getElementById(clientId.replace('_1_selected','_'+i+'_type1'));
var frmSchoolAdditional = document.getElementById(clientId.replace('_1_selected','_'+i+'_additional'));
frmSchoolSelected.disabled = !isYes;
frmSchoolAge.disabled = isYes;
frmSchoolType.disabled = isYes;
frmSchoolAdditional.disabled = isYes;
}
}
A few notes on your approach.
Be aware of how you're using this as it means different things in different contexts. In your case it would be better to pass in the index of the row you're toggling. Your server side code most likely knows what row it's currently generating so this should be easy to accomplish.
As others pointed out, you are mixing client side and server side. In this case i is a client side variable that you're trying to use in a '<%=c_'... which is a server side context
I'm not quite sure why you're putting a + into what should be a variable name, but using a plus sign as part of a variable name isn't legal in JavaScript
switchElement in this case isn't a CheckboxList as you're expecting it to be, it's just an html span element and as such won't have a meaningful value property. You have to look at the actual input elements inside it and see if the yes element is checked (for example).
If you were to go with a JavaScript solution you would need code along these lines
function toggle(i) {
var schoolSelected = document.getElementById('c_' + i + '_school_selected_0').checked;
// client side names of variables will be predictable so to an extent you can get away with
// hard-coding them. Not the best practice, but it'd work
var frmSchoolSelected = document.getElementById('c_' + i + '_selected');
var frmSchoolAge = document.getElementById('c_' + i + '_type');
var frmSchoolType = document.getElementById('c_' + i + '_type1');
var frmSchoolAdditional = document.getElementById('c_' + i + '_additional');
// JavaScript, like some other languages lets you chain assignments like this
frmSchoolSelected.disabled =
frmSchoolAge.disabled =
frmSchoolType.disabled =
frmSchoolAdditional.disabled = !schoolSelected;
}
If you were to approach this from jQuery side I would suggest making a few changes to your HTML as well. Your output can be thought of as a list of mini-forms so instead of having one large table with different rows corresponding to different parts, create a list (or a table with a single column if you aren't ready to give up on table based layout quite yet).
New HTML
<ul>
<li class="school1">
<!-- school information form goes here -->
...
<span id="c_1_school_selected" class="toggle" onclick='toggle("school1")'>
...
</li>
<li class="school2">
<!-- school information form goes here -->
...
<span id="c_1_school_selected" class="toggle" onclick='toggle("school2")'>
...
</li>
...
</ul>
New code
function toggle(row) {
var allInputs = $("#" + row + " :input")
.not(".toggle input:radio");
var state = $(".toggle :checked").val();
if (state == "Yes") {
allInputs.removeAttr("disabled");
} else {
allInputs.attr("disabled", "disabled");
}
}
There are two nice things about this approach:
You are no longer relying on knowing what the ClientID will be as you're dealing with input elements as input elements
You can now refactor this input form into some sort of a repeating control (like a ListView) so if you decide you'd like to change how each row is formatted, it'll be very easy to do (since it'll all be in one place).
I got there eventually, once I had worked out how to add the onclick attribute to the input tag instead of the span tag I could then concentrate on the javascript function.
Code behind
Adds onclick to input tag.
Dim newRadioYes As New RadioButton
newRadioYes.Text = "Yes"
newRadioYes.ID = "c_" & childID & "_school_selected_0"
newRadioYes.Attributes.Add("onclick", "javascript:toggle(this, " & childID & ");")
newRadioYes.Attributes.Add("value", "Yes")
newRadioYes.GroupName = "c_" & childID & "_school_selected"
Dim newRadioNo As New RadioButton
newRadioNo.Text = "No"
newRadioNo.ID = "c_" & childID & "_school_selected_1"
newRadioNo.Attributes.Add("onclick", "javascript:toggle(this, " & childID & ");")
newRadioNo.Attributes.Add("value", "No")
newRadioNo.GroupName = "c_" & childID & "_school_selected"
Generated HTML form
<form method="post" action="schoolingform.aspx" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'Button1')" id="form1">
<table id="Table1" cellspacing="0" cellpadding="0" style="border-width:0px;border-collapse:collapse;">
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><input id="c_1_school_selected_0" type="radio" name="c_1_school_selected" value="Yes" onclick="javascript:toggle(this, 1);" />
<label for="c_1_school_selected_0">Yes</label>
<input id="c_1_school_selected_1" type="radio" name="c_1_school_selected" value="No" onclick="javascript:toggle(this, 1);" />
<label for="c_1_school_selected_1">No</label></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Fred Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_1_selected" type="text" id="c_1_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_1_id" id="c_1_id" value="26" /></td>
<td><select name="c_1_type" id="c_1_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_1_type1" id="c_1_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_1_additional" rows="6" cols="30" id="c_1_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><input id="c_2_school_selected_0" type="radio" name="c_2_school_selected" value="Yes" onclick="javascript:toggle(this, 2);" />
<label for="c_2_school_selected_0">Yes</label>
<input id="c_2_school_selected_1" type="radio" name="c_2_school_selected" value="No" onclick="javascript:toggle(this, 2);" />
<label for="c_2_school_selected_1">No</label></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Sara Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_2_selected" type="text" id="c_2_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_2_id" id="c_2_id" value="27" /></td>
<td><select name="c_2_type" id="c_2_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_2_type1" id="c_2_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_2_additional" rows="6" cols="30" id="c_2_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td align="right" colspan="5"></td>
</tr>
</table>
<input type="hidden" name="iChild" id="iChild" value="2" />
<input type="submit" name="Button1" value="Next" id="Button1" class="submitBtn" />
Javascript function
function toggle(switchElement, childID) {
var frmSelected = document.getElementsByName('c_' + childID + '_school_selected');
var frmSchoolSelected = document.getElementById('c_' + childID + '_selected');
var frmSchoolAge = document.getElementById('c_' + childID + '_type');
var frmSchoolType = document.getElementById('c_' + childID + '_type1');
var frmSchoolAdditional = document.getElementById('c_' + childID + '_additional');
if (switchElement.value == 'Yes') {
frmSchoolSelected.disabled = false;
frmSchoolAge.disabled = true;
frmSchoolType.disabled = true;
frmSchoolAdditional.disabled = true;
}
else {
frmSchoolSelected.disabled = true;
frmSchoolAge.disabled = false;
frmSchoolType.disabled = false;
frmSchoolAdditional.disabled = false;
}
}
Thanks to those who pointed me in the right direction, much appreciated.