Below is a sample code. Whenever i validate i don't want to highlight the select field in red. But just want to show the error beside the select field in Red.
HTML after click submit
<select name="event" class="control-label error">
<option value="">Select</option>
<option value="1">Sample 1</option>
</select>
<label for="event" generated="true" class="error" style="display: inline-block;"><span style="padding:6px; "> Please select something </span></label>
UI
jQuery Validation
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
}
});
if you are using jquery validate library.. Doc says just add valid class on elements where you don't want the border styling.
hope this will help..
Actually required is Html 5 that should show the error in red color only
while in validation use id to call or validate then use that id in style with your need color
ex
#errorBox1,
#errorBox2,
#errorBox3,
#errorBox4,
#errorBox5,
#errorBox6,
#errorBox7,
#errorBox8,
#errorBox9,
#errorBox10
{
color:blue;
}
This is my external stylesheet
function validate()
{
var status = true;
var a = document.form.Name.value;
var b = document.form.Password.value;
var c = document.form.Cpassword.value;
var d = document.form.Address.value;
var e = document.form.Email.value;
var f = document.form.Mobile.value;
if( a == "" )
{
document.getElementById("errorBox1").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox1").innerHTML = "";
}
if( b == "" )
{
document.getElementById("errorBox2").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox2").innerHTML = "";
}
if( c == "" )
{
document.getElementById("errorBox3").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox3").innerHTML = "";
}
if (b!=c)
{
document.getElementById("errorBox10").innerHTML = "*Password does not match";
status = false;
}
else
{
document.getElementById("errorBox10").innerHTML = "";
}
if( d == "" )
{
document.getElementById("errorBox4").innerHTML = "*Please fill required";
status = false;
}
else
{
document.getElementById("errorBox4").innerHTML = "";
}
if(e == "" || e.indexOf("#", 0) < 0 || e.indexOf(".", 0) < 0 )
{
document.getElementById("errorBox5").innerHTML = "*Please fill your valid email id ";
status = false;
}
else
{
document.getElementById("errorBox5").innerHTML = "";
}
if(f == "" || f.length !=10 || f.charAt(0)!="9" )
{
document.getElementById("errorBox6").innerHTML = "*Mobile no must be 10 digits";
status = false;
}
else
{
document.getElementById("errorBox6").innerHTML = "";
}
if ((document.form.radio1[0].checked == false) && (document.form.radio1[1].checked == false))
{
document.getElementById("errorBox7").innerHTML = "*Select your Gender";
status = false;
}
else
{
document.getElementById("errorBox7").innerHTML = "";
}
if ((document.form.chk[0].checked == false) && (document.form.chk[1].checked == false))
{
document.getElementById("errorBox8").innerHTML = "*Please fill the checkbox";
status = false;
}
else
{
document.getElementById("errorBox8").innerHTML = "";
}
if (document.form.comment.value == "")
{
document.getElementById("errorBox9").innerHTML = "*Please share your feedback";
status = false;
}
else
{
document.getElementById("errorBox9").innerHTML = "";
}
return status;
}
</script>
</head>
<body>
<div class="rm">
<form name="form" method="post" onsubmit ="return validate();" action=" ">
Name : <input type="text" name="Name" onkeyup="validate();" /><div id="errorBox1"></div>
<br>
Password : <input type="password" name="Password" onkeyup="validate();" /><div id = "errorBox2"></div>
<br>
Confirm Password : <input type="password" name="Cpassword" onkeyup="validate();" /><div id = "errorBox3"></div> <div id = "errorBox10"></div>
<br>
Address : <input type="text" name="Address" onkeyup="validate();" /><div id = "errorBox4"></div>
<br>
Email : <input type="text" name="Email" onkeyup="validate();" /><div id = "errorBox5"></div>
<br>
Mobile No :<input type="text" name="Mobile" onkeyup="validate();" /><div id = "errorBox6"></div>
<br>
Gender : Male<input name="radio1" type="radio" value="Male" onclick="validate();"/>
Female<input name="radio1" type="radio" value="Female" onclick="validate();"/><div id = "errorBox7"></div>
<br>
Computer Courses: <input type="checkbox" name="chk" onclick="validate();" value="Php"/> Php
<input type="checkbox" name="chk" onclick="validate();" value="ccna"/> Ccna <div id = "errorBox8"></div>
<br>
CommentBox : <textarea cols = "25" name= "comment" onkeyup="validate();" /></textarea><div id = "errorBox9"></div>
<br>
<div class="submit">
<input type="submit" name="submit" value="Submit" >
<input type="reset" value="Reset"></submit>
Thanks everyone for the response. I just did the following in validate part. I just added a Highlight and it worked. I seriously don't know how it worked. But thanks to Sathvik Cheela for giving an idea about highlight and unhighlight.
$("form").validate({
onkeyup:false,
async: false,
rules: {
event: {
required: true
}
},
messages: {
event: {
required: "<span style='padding:6px; '> Please select Something </span>"
}
},
highlight: function(element, errorClass) {
}
});
UI (Now)
Related
I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!
Here is the HTML code:
<form id="contactform" action="">
<label> Name
<input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />
</label>
<label> Last Name
<input name="lastname" type="text" id="lastname" maxlength="150" />
</label>
<label> Address
<input name="address" type="text" id="address" maxlength="200" />
</label>
<label> Postcode
<input name="postcode" type="text" id="postcode" maxlength="50" />
</label>
<label> City
<input name="city" type="text" id="city" maxlength="100" />
</label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />
Here is the javascript code:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
if (firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if (lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if (address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if (postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
if (city.value == "") {
alert("Make sure the city field is filled");
return false;
}
return true;
}
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var errMsg = "";
if(firstname.value == "") {
errMsg+="Make sure the first name field is filled\n";
}
if(lastname.value == "") {
errMsg+="Make sure the last name field is filled\n";
}
if(address.value == "") {
errMsg+="Make sure the address field is filled\n";
}
if(postcode.value == "") {
errMsg+="Make sure the post code field is filled\n";
}
if(city.value == "") {
errMsg+="Make sure the city field is filled\n";
}
if(errMsg != "") {
alert(errMsg);
return false;
}else {
return true;
}
}
<form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" />
This should do it, would need to format it how you like. Also there are several libs out there that handle this for you eg. http://formvalidation.io/
You can use HTML validation, i.e. the [required] attribute:
<form id="contactform" action="">
<label> Name
<input required name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus"/>
</label>
<label> Last Name
<input required name="lastname" type="text" id="lastname" maxlength="150">
</label>
<label> Address
<input required name="address" type="text" id="address" maxlength="200">
</label>
<label> Postcode
<input required name="postcode" type="text" id="postcode" maxlength="50">
</label>
<label> City
<input required name="city" type="text" id="city" maxlength="100">
</label>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>
You can put all the blank fields in a string, like this:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var missedFields = ""
if (firstname.value == "") {
missedFields += "First name.\n";
//alert("Make sure the first name field is filled");
//return false;
}
if (lastname.value == "") {
missedFields += "Last name.\n";
//alert("Make sure the last name field is filled");
//return false;
}
if (address.value == "") {
missedFields += "Adress.\n";
//alert("Make sure the address field is filled");
//return false;
}
if (postcode.value == "") {
missedFields += "Post code.\n";
//alert("Make sure the post code field is filled");
//return false;
}
if (city.value == "") {
missedFields += "City.\n";
//alert("Make sure the city field is filled");
//return false;
}
if (missedFields.length > 0) {
alert("Complete all fields:\n" + missedFields);
return false
}
return true;
}
<form id="contactform" action="">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />
Here's one way that you could do it - adding to a single alert string:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var alertstring = "Make sure all fields are filled! Currently missing:"
if(firstname.value == "") {
alertstring += " -First Name-"
}
if(lastname.value == "") {
alertstring += " -Last Name-"
}
if(address.value == "") {
alertstring += " -Address-"
}
if(postcode.value == "") {
alertstring += " -Postal Code-"
}
if(city.value == "") {
alertstring += " -City-"
}
if(alertstring == "Make sure all fields are filled! Currently missing:")
{
return true;
}
else {
alert(alertstring);
return false;
}
}
You can create a variable and add the validation messgae to that and display it.A sample
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var text = "Make sure";
var valid = true;
if(firstname.value == "") {
text+= " the first name ";
valid = false;
}
if(lastname.value == "") {
text += ( !valid ? '& ' : '')+ " the last name "
valid = false;
}
if(address.value == "") {
text += ( !valid ? '& ' : '')+ " the address ";
valid = false;
}
if(postcode.value == "") {
text += ( !valid ? '& ' : '')+ " the postcode ";
valid = false;
}
if(city.value == "") {
text += ( !valid ? '& ' : '') + " the city ";
valid = false;
}
if(!valid){
text+= " is Filled";
alert(text);
return false;
}
return true;
}
<form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" />
This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 5 years ago.
I have created an alert box which will output the details from the form I am now wondering how I start the Java validation part so that if the form is filled in
correctly an alert box with the form details will show however if it is wrong instruct the user to fill in the invalid boxes.
HTML
<form id="foo" onsubmit="formAlert(); return false;" method="POST">
<p><label for="first_name">First Name<label><input type="text" id="first_name" value="" /></p>
<p><label for="last_name">Last Name<label><input type="text" id="last_name" value="" /></p>
<p><label for="Phone_num">Phone Number<label><input type="number" id="phone_num" value="" /></p>
<p><input type="submit" value="click me" onclick=""/></p>
</form>
Java Script
function formAlert() {
alert_string = '';
var userName = document.getElementById('first_name').value;
var userLastName = document.getElementById('last_name').value;
var phoneno = document.getElementById('phone_num').value;
if(userName === "" || userName === null){
alert("Please enter name");
}
if(userLastName === "" || userLastName === null){
alert("Please enter lastname");
}
else if(phoneno === "/^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;" || phoneno === null){
alert("Please enter Phone number");
}
else{
alert_string += userName + " ";
alert_string += userLastName;
alert_string += phoneno;
alert(alert_string);
}
}
Here's a quick and simple solution. Add this to your javascript code. Hope it helps!
function validatePhone(inputtxt) {
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
return phoneno.test(inputtxt)
}
function formAlert() {
alert_string = '';
var userName = document.getElementById('first_name').value;
var userLastName = document.getElementById('last_name').value;
var phoneno = document.getElementById('phone_num').value;
if(userName === "" || userName === null){
alert("Please enter name");
}
if(userLastName === "" || userLastName === null){
alert("Please enter lastname");
}
else if(!validatePhone(phoneno)){ alert("Please enter 10 digits for phone number"); }
else{
alert_string += userName + " ";
alert_string += userLastName + " ";
alert_string += phoneno;
alert(alert_string);
}
}
To check for email simple use required. Something like this:
<input type="email" name="email" required>
There are many ways to validate phone number. Here's a good example: Credit goes to: https://stackoverflow.com/a/18376246/4084160
There is other way to do that. it is a good approach if you have many inputs
<html>
<style>
.required
{
border: 1px solid #F00;
padding: 2px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="foo" onsubmit="formAlert(); return false;" method="POST">
<p><label for="first_name">First Name<label><input type="text" id="first_name" value="" /></p>
<p><label for="last_name">Last Name<label><input type="text" id="last_name" value="" /></p>
<p><input type="submit" value="click me" onclick=""/></p>
</form>
<div id="msgRequired" style="display: none;">
<p>required Field!</p>
</div>
<script>
function formAlert() {
alert_string = '';
var cont = 0;
$("#foo input").not(':hidden').each(function () {
if ($(this).val() == "") {
$(this).addClass("required");
cont++;
}
else
{
$(this).removeClass("required");
}
});
if(cont == 0)
{
alert_string = alert_string + document.getElementById('first_name').value;
alert_string = alert_string + ' ';
alert_string = alert_string + document.getElementById('last_name').value;
alert(alert_string);
$("#msgRequired").hide();
}
else
{
$("#msgRequired").show();
}
}
</script>
</html>
When I hit my submit button it just goes straight to the php page. The javascript does not load at all. This is very confusing because I am receiving no errors in console nor when I validate the javascript using external error checkers (such as JShint). The javascript was working at one point in my coding so I have no idea why it stopped working.
JAVASCRIPT:
//jQuery
$(document).ready(function() {
// listen for a click event on any radio element
$('input[type="radio"]').click(function() {
// get the id of the clicked element
var id = $(this).attr('id');
// fade out any existing image elements
$('img').fadeOut(800, function() {
// fade in the image element with the id we're after, with a half second delay (500 milliseconds)
setTimeout(function() {
$('#' + id + 'i').fadeIn(800);
}, 500);
});
});
});
function checkInput() {
var firstName = document.getElementById("fn");
var lastName = document.getElementById("ln");
var email = document.getElementById("email");
var emailR = document.getElementById("emailR");
var postal = document.getElementById("pc");
var city = document.getElementById("city");
var sA = document.getElementById("sA");
var qN = document.getElementById("qty");
var provy = document.getElementById("prov");
var foc = false;
var error = "";
var letters = /^[a-zA-Z]+$/;
var numbers = /^\d+$/;
var letNm = /^(?=.*[a-zA-Z])(?=.*[0-9])/;
//First-Name Validation
if (firstName.value == "" || firstName.value.length > 15 || firstName.value.length < 2 || !firstName.value.match(letters)) {
error += "\n Please enter a valid first name.";
if (foc == false) {
document.getElementById("fn").focus();
foc = true;
}
}
//Last-Name Validation
if (lastName.value == "" || lastName.value.length > 15 || lastName.value.length < 2 || !lastName.value.match(letters)) {
error += "\n Please enter a valid last name";
if (foc == false) {
document.getElementById("ln").focus();
foc = true;
}
}
//street Address
if (sA.value == "" || sA.value.length < 6 || sA.value.length > 30 || !sA.value.match(letNm)) {
error += "\n Please enter a valid street address (must contain letters and numbers, \n and be more than 6 less than 30 chars) ";
if (foc == false) {
document.getElementById("sA").focus();
foc = true;
}
}
//City Validation
if (city.value == "" || city.value.length > 20 || city.value.length < 2 || !city.value.match(letters)) {
error += "\n Please enter a valid city (more than 2 characters, less than 20, all letters)";
if (foc == false) {
document.getElementById("city").focus();
foc = true;
}
}
//Province Validation
var select = provy.options[provy.selectedIndex].value;
if (select == "s") {
error += "\n Please choose a province";
if (foc == false) {
document.getElementsByName("prov").focus();
foc = true;
}
}
//Email Validation
var ei = email.value.lastIndexOf('#');
var dot = email.value.lastIndexOf('.');
if (email.value == "" || email.value.length < 7 || email.value.length > 50 || ei == -1 || dot == -1 || dot < ei + 2) {
error += "\n Please enter a valid email address \n (must have an \"#\" symbol followed by a \".\")";
if (foc == false) {
document.getElementById("email").focus();
foc = true;
}
} else if (emailR.value != email.value) {
error += "\n Your email addresses did not match";
if (foc == false) {
document.getElementById("emailR").focus();
foc = true;
}
}
//Postal Code Validation
var pi = postal.value.lastIndexOf(" ");
var code = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
if (postal.value == "" || postal.value.length != 7 || !postal.value.match(code) || pi != 3) {
error += "\n Please enter a valid Canadian postal code. E.g. \"N3H 1M1\" ";
if (foc == false) {
document.getElementById("pc").focus();
foc = true;
}
}
//Album selection Validation
var jay = document.getElementsById("jayz");
if (!isOneChecked(jay)) {
error += "\n Please choose an album to purchase";
if (foc == false) {
document.getElementsByName("jayz").focus();
foc = true;
}
}
//quantity validation
if (qN.value == "" || qN.value > 99 || qN.value < 1 || !qN.value.match(numbers)) {
error += "\n Please enter a quantity between 1-99";
if (foc == false) {
document.getElementByName("qntty").focus();
foc = true;
}
}
//error validation:error2 boolean returns either true or false
var error2 = false;
if (foc == false) {
alert("Thank you for signing up!");
error2 = true;
} else {
alert(error);
error2 = false;
}
return error2;
}
//function that trims and converts string to properCase
function properCaseTrim(string) {
var str = string.length;
for (var i = 0; i < str; i++) {
var letter = string.charAt(i);
if (letter == " ") {
string = string.replace(/^\s\s*/, ''); // Remove Preceding white space
string = string.replace(/\s\s*$/, ''); // Remove Trailing white space
}
string = string.charAt(0).toUpperCase() + string.slice(1);
}
return string;
}
function isOneChecked() {
// All <input> tags...
var chx = document.getElementsByTagName('input');
for (var i = 0; i < chx.length; i++) {
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
return true;
}
}
// End of the loop, return false
return false;
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Assignment #4</title>
<link rel="icon" type="image/x-icon" href="images/favi.ico" />
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
<script type="text/javascript" src="javascript/jquery-1.12.1.js"></script>
<script type ="text/javascript" src="javascript/function.js"></script>
</head>
<body>
<header>
<h1>Jay-Z Albums</h1>
</header>
<fieldset id = "field1">
<legend>Shipping Info</legend>
<p id ="p">All Fields Are Mandatory </p>
<form method = "post" name= "user creation form" onsubmit="return checkInput();" action = "php/validate.php">
First name<br>
<input type="text" name="firstName" id ="fn" onblur="this.value = properCaseTrim(this.value)" value= "" autofocus><br>
Last name<br>
<input type="text" name="lastName" id = "ln" onblur="this.value = properCaseTrim(this.value)" value= ""><br>
Street Address<br>
<input type="text" name="streetAddress" id = "sA" placeholder="123 Main St." onblur="this.value = properCaseTrim(this.value)" value= "" ><br>
<label>
City <br>
<input type="text" name="city" id="city" onblur="this.value = properCaseTrim(this.value)" value= "">
</label>
<br>
Province <br>
<select name ="prov" id ="prov">
<option value = "s">-select-</option>
<option value="Alberta">Alberta</option>
<option value="British Columbia">British Columbia</option>
<option value="Manitoba">Manitoba</option>
<option value="New Brunswick">New Brunswick</option>
<option value="Newfoundland and Labrador">Newfoundland and Labrador</option>
<option value="Nova Scoti">Nova Scotia</option>
<option value="Ontario">Ontario</option>
<option value="Prince Edward Island">Prince Edward Island</option>
<option value="Quebec">Quebec</option>
<option value="Saskatchewan">Saskatchewan</option>
<option value="Northwest Territories">Northwest Territories</option>
<option value="Nunavut">Nunavut</option>
<option value="Yukon">Yukon</option>
</select>
<br>
<label>
Postal Code <br>
<input type="text" name="pc" id="pc" placeholder="A1A 1A1" onblur="this.value = this.value.toUpperCase(); this.value = properCaseTrim(this.value)" value= ""> <br>
</label>
<label>
Email Address<br>
<input type="text" name="email" id="email" value= ""> <br>
</label>
<label>
Repeat Email Address <br>
<input type="text" name="emailR" id="emailR" value= "" > <br>
</label>
<br>
</fieldset>
<fieldset id = "field3">
<legend>Order </legend>
<p> One Album Per Order</p>
<p> Prices shown are without tax </p>
<input type = "radio" name ="jayz" value="rDbt" id= "rD">[1996]Reasonable Doubt-$25 <br>
<input type = "radio" name ="jayz" value="bPrint" id= "bP1">[2001]The Blueprint-$10<br>
<input type = "radio" name ="jayz" value="bPrint2" id = "bP2">[2002]The Blueprint 2-$15<br>
<input type = "radio" name ="jayz" value="kCome" id ="kC">[2006]Kingdom Come-$10<br>
<input type = "radio" name ="jayz" value="bPrint3" id ="bP3">[2009]The Blueprint 3-$25<br>
<input type = "radio" name ="jayz" value="mCarta" id ="mC">[2013]Magna Carta Holy Grail-$30<br>
<div id="q">
# of Albums:
<input type="text" name="quant" id="qty">
</div>
</fieldset>
<aside>
<div id = "divvy">
<img class = "hidden" src="images/rDoubt.jpg" alt="Reasonable Doubt" height="400px" width="400px" id= "rDi">
<img class = "hidden" src="images/bPrint.jpg" alt="the Blueprint" height="400px" width="400px" id= "bP1i">
<img class = "hidden" src="images/bPrint2.jpg" alt="the Blueprint 2" height="400px" width="400px" id = "bP2i">
<img class = "hidden" src="images/kCome.jpg" alt="Kingdom Come" height="400px" width="400px" id ="kCi">
<img class = "hidden" src="images/bPrint3.jpg" alt="the Blueprint 3" height="400px" width="400px" id ="bP3i">
<img class = "hidden" src="images/mCarta.jpg" alt="Magna Carta" height="400px" width="400px" id ="mCi">
</div>
</aside>
<input id="button" type="submit" value="Submit Order" >
</form>
</body>
</html>
Reverse the order of these script tags: (The jquery one should be first)
<script type ="text/javascript" src="javascript/function.js"></script>
<script type="text/javascript" src="javascript/jquery-1.12.1.js"></script>
I suspect your jquery code in function.js is not working due to this issue.
Thats the default behavior of <input type="submit"/>, you have to override it:
$('form').on('submit',function(e){
e.prevetDefault();
//do your JS processing here, call a function and finally make an AJAX request
checkInput();
});
That should do.
On a separate note, I dont think 'name' attribute with spaces is valid. It is best to be kept unique/ or treat as a key or identifier.
This code below is working but I want some modification in this code.
When user is not filling the box it is displaying error box that part is working but after filling it should disappear. So please anyone help me to solve the issue.
I have post the code here including html and java script so just copy and run it it will work and try to resolve my issue.
<html>
<head>
<script type="text/javascript">
function validate()
{
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
if( fname == "" )
{
document.form.Name.focus() ;
document.getElementById("errorBox1").innerHTML = "enter the first name";
return false;
}
if( lname == "" )
{
document.form.Lame.focus() ;
document.getElementById("errorBox2").innerHTML = "enter the last name";
return false;
}
if( same == "" )
{
document.form.Same.focus() ;
document.getElementById("errorBox3").innerHTML = "enter the Same name";
return false;
}
}
</script>
</head>
<body>
<form name="form" >
SSS :<input type="text" name="Name" value="" class="input_name" ><div id="errorBox1"> </div>
<br>
SSmjhjk :<input type="text" name="Lame" value="" class="input_name" ><div id = "errorBox2"></div>
<br>
nngb :<input type="text" name="Same" value="" class="input_name" ><div id = "errorBox3"></div>
<input type=button onClick="validate()" value=check>
</form>
In my first notice, You have the syntax error in your script. In your last condition you have written the code like if else if( same == "" ). This is wrong.
If you want check and display error for all the textbox at the same time, then you need to remove the return property from the script. Update your script like below.
function validate()
{
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
document.getElementById("errorBox1").innerHTML ="";
document.getElementById("errorBox2").innerHTML ="";
document.getElementById("errorBox3").innerHTML ="";
if( fname == "" )
{
document.getElementById("errorBox1").innerHTML = "enter the first name";
}
if( lname == "" )
{
document.getElementById("errorBox2").innerHTML = "enter the last name";
}
if( same == "" )
{
document.getElementById("errorBox3").innerHTML = "enter the Same name";
}
}
HTML
<form name="form" >
SSS :<input type="text" name="Name" value="" class="input_name" onkeyup="validate();" /><div id="errorBox1"> </div>
<br>
SSmjhjk :<input type="text" name="Lame" onkeyup="validate();" value="" class="input_name" /><div id = "errorBox2"></div>
<br>
nngb :<input type="text" name="Same" onkeyup="validate();" value="" class="input_name" /><div id = "errorBox3"></div>
<input type="button" onclick="validate();" value="check" />
</form>
Fiddle Demo
Try this , this might work for you
function validate() {
var fname = document.form.Name.value;
var lname = document.form.Lame.value;
var same = document.form.Same.value;
if (fname == "") {
document.form.Name.focus();
document.getElementById("errorBox1").innerHTML = "enter the first name";
return false;
} else {
document.getElementById("errorBox1").innerHTML = "";
}
if (lname == "") {
document.form.Lame.focus();
document.getElementById("errorBox2").innerHTML = "enter the last name";
return false;
} else {
document.getElementById("errorBox2").innerHTML = "";
}
if (same == ""){
document.form.Same.focus();
document.getElementById("errorBox3").innerHTML = "enter the Same name";
return false;
} else {
document.getElementById("errorBox3").innerHTML = "";
}
}
use input type like this
<input type="text" id="fname" onkeyup="validate()">
This will help you
If you want to use javascript only, you can hide the error div:
document.getElementById("errorBox1").style.display = 'none';