I'm trying to change the value of the submit button, only after required fields are filled. but as per my below code the value is changing even the required fields are not filled, additionally I'm need advice on how to mark at least one checkbox field as required.
$('#formSubmit').click(function(){
$(this).val("Processing");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>Call Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="CAll Me">
</label>
<br />
<label>Email Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="Email Me">
</label>
<br />
<hr />
<input type="text" id="formName" name="formName" placeholder="Please Enter Your Name" required>
<br />
<input type="email" id="formEmail" name="formEmail" placeholder="Please Enter Your Email Address" required>
<br />
<input type="text" id="formMobile" name="formMobile" placeholder="Please Enter Your Contact No" min="10" max="10" required>
<br />
<input type="submit" id="formSubmit" value="Submit" />
</form>
You can listen to submit event instead:
$(document).ready(function(e) {
$('#myForm').on('submit', function(e){
e.preventDefault();
$('#formSubmit').val("Processing");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form id="myForm">
<label>Call Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="CAll Me">
</label>
<br />
<label>Email Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="Email Me">
</label>
<br />
<hr />
<input type="text" id="formName" name="formName" placeholder="Please Enter Your Name" required>
<br />
<input type="email" id="formEmail" name="formEmail" placeholder="Please Enter Your Email Address" required>
<br />
<input type="text" id="formMobile" name="formMobile" placeholder="Please Enter Your Contact No" min="10" max="10" required>
<br />
<input type="submit" id="formSubmit" value="Submit" />
</form>
</body>
$(document).ready(function(e) {
function validateForm() {
var isValid = true;
$('input[required]').each(function() {
if ( $(this).val() === '' ){
isValid = false;
}
});
return isValid;
}
$('#formSubmit').click(function(){
if(validateForm()) {
$(this).val("Processing");
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
<label>Call Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="CAll Me">
</label>
<br />
<label>Email Me
<input type="checkbox" name="contactMethod[]" id="contactMethod[]" value="Email Me">
</label>
<br />
<hr />
<input type="text" id="formName" name="formName" placeholder="Please Enter Your Name" required>
<br />
<input type="email" id="formEmail" name="formEmail" placeholder="Please Enter Your Email Address" required>
<br />
<input type="text" id="formMobile" name="formMobile" placeholder="Please Enter Your Contact No" min="10" max="10" required>
<br />
<input type="submit" id="formSubmit" value="Submit" />
</form>
</body>
I'm adding my solution since nobody seems to answer the second part of the question. You need to modify your markup a little as done below in the answer.
function makeChecks() {
checkBoxes = $("input:checked"); //Find checked checkboxes
if (checkBoxes.length) { //Only submit if some checked checkbox(es) exist
$('#exampleForm').find('input').each(function() {
if ($(this).prop('required') && $(this).val() !== "") {
$("#formSubmit").val("Processing");
}
});
}
}
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="exampleForm">
<label>Call Me
<input type="checkbox" name="contactMethod[]"
id="contactMethod[]" value="CAll Me">
</label>
<br />
<label>Email Me
<input type="checkbox" name="contactMethod[]"
id="contactMethod[]" value="Email Me">
</label>
<br />
<hr />
<input type="text" id="formName" name="formName" placeholder="Please Enter Your Name" required>
<br />
<input type="email" id="formEmail" name="formEmail" placeholder="Please Enter Your Email Address" required>
<br />
<input type="text" id="formMobile" name="formMobile" placeholder="Please Enter Your Contact No" min="10" max="10" required>
<br />
<input type="submit" id="formSubmit" onclick="makeChecks()" value="Submit" />
</form>
</body>
Id must be unique. Unique id must be assigned to each checkbox. Add required attribute to the checkbox controls.
<label>Call Me
<input type="checkbox" name="contactMethod[]" id="callMe" value="CAll Me" required>
</label>
<br />
<label>Email Me
<input type="checkbox" name="contactMethod[]" id="emailMe" value="Email Me" required>
</label>
You can use $(elem).val() != '' to check if a input element has been entered.
For checkbox, you can use $(elem).prop('checked') to check if a checkbox has been checked.
$(document).ready(function(e) {
$('#formSubmit').click(function(e){
if((!$('#callMe').prop('checked') || !$('#emailMe').prop('checked')) && $('#formName').val() != '' && $('#formEmail').val() != '' && $('#formMobile').val() != '')
$(this).val("Processing");
});
});
https://jsfiddle.net/snehansh/nwh0vct8/3/
Related
I have been trying to make a form in which as and when a checkbox is checked, the button is enabled. I tried jquery and javascript, but they are not helping.
HTML code of form:
<form>
Name*: <input type="text" size="20" name="name" required /> <br /><br />
Surname: <input type="text" size="20" /> <br />
<br /><br />
Mobile number: <input type="tel" size="15" /> <br /><br />
E-mail id*: <input type="Email" size="30" name="usr_id" required /> <br /><br />
Password*: <input type="Password" size="30" id="pw1" required /> <br /><br />
Confirm Password*: <input type="password" size="30" id="pw2" required /> <br /><br /><br /><br />
I accept the terms and conditions <input class="chk" type="checkbox" id="tc" /><br /><br />
<input type="submit" id="btn" class="btn btn-lg btn-primary" value="Sign up" onclick="form_function()"/>
</form>
Javascript-form_function:
function form_function(){
var pw = document.getElementById(pw1).value;
var conf_pw = document.getElementById(pw2).value;
if (pw == conf_pw){
window.location.href('http://www.google.com/sgn_up_conf');
} else{
if (conf_pw == ""){
window.alert("Please confirm your password");
} else {
if (pw == conf_pw == ""){
window.alert("Please enter a password");
} else {
if (pw == "") {
window.alert("How can you confirm a password if you have not written anything?");
} else {
window.alert("Please make sure that you have confirmed the password properly");
}
}
}
}
};
Javascript to conditionally disable button:
$('#btn').prop("disabled", true);
$('#tc').click(function() {
if ($(this).is(':checked')) {
$('#btn').prop("disabled", false);
} else {
$('#btn').attr('disabled',true);}
}
});
form_function() is working fine, but the checkbox-button relation is not working out. Even when the checkbox is not checked, the button is in enabled state, and caries out form_function().
*In this new edit, I have put up the updated form_function(), this time, I have included all possibilities of the two password fields.
I would suggest you adjust your code to use a simpler set. I changed your markup to a bit more conventional, not specifically required, I removed all the <br /> and used CSS to space stuff out.
As to why your code did not work?
It has a syntax error.
Using the CLICK event, on the first click it gets checked which is OK however if you use the keyboard to check/un-check, it does not fire thus you should use the change event to ensure actions that can change it are accounted for.
You have an issue with the href and that odd event hooking, you really want to set it instead. window.location.href = "www.google.co.in/sgn_conf";
$('#btn').on('click', function() {
if ($('#pw1').val() == $('#pw2').val()) {
window.location.href = "www.google.co.in/sgn_conf";
} else {
window.alert("Please make sure that both the password fields have the same text");
}
}).prop("disabled", true);
$('#tc').on('change', function() {
$('#btn').prop("disabled", !this.checked);
});
form div {
margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div>
<label> Name*:
<input type="text" size="20" name="name" required />
</label>
</div>
<div>
<label>Surname:
<input type="text" size="20" />
</label>
</div>
<div>
<label>Mobile number:
<input type="tel" size="15" />
</label>
</div>
<div>
<label>E-mail id*:
<input type="Email" size="30" name="usr_id" required />
</label>
</div>
<div>
<label>Password*:
<input type="Password" size="30" id="pw1" required />
</label>
</div>
<div>
<label>Confirm Password*:
<input type="password" size="30" id="pw2" required />
</label>
</div>
<div>
<label>I accept the terms and conditions
<input class="chk" type="checkbox" id="tc" />
</label>
</div>
<div>
<input type="submit" id="btn" class="btn btn-lg btn-primary" value="Sign up" />
</div>
</form>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form>
Name*: <input type="text" size="20" name="name" required /> <br /><br />
Surname: <input type="text" size="20" /> <br />
<br /><br />
Mobile number: <input type="tel" size="15" /> <br /><br />
E-mail id*: <input type="Email" size="30" name="usr_id" required /> <br /><br />
Password*: <input type="Password" size="30" id="pw1" required /> <br /><br />
Confirm Password*: <input type="password" size="30" id="pw2" required /> <br /><br /><br /><br />
I accept the terms and conditions <input class="chk" type="checkbox" id="tc" /><br /><br />
<input type="submit" id="btn" class="btn btn-lg btn-primary" value="Sign up" disabled="disabled" onclick="form_function()"/>
</form>
</body>
<script>
function form_function(){
var pw1 = document.getElementById('pw1').value;
var pw2 = document.getElementById('pw2').value;
if (pw1 == pw2){
document.getElementById('btn').onclick = window.location.href("www.google.co.in/sgn_conf");
} else {
document.getElementById('btn').onclick = window.alert("Please make sure that both the password fields have the same text");
}
}
$("#tc").change(function () {
if (this.checked) {
$("#btn").prop("disabled", false);
}
else {
$("#btn").prop("disabled", true);
}
});
</script>
</html>
Check the snippet.
Could it be that you have a extra }?
...
$('#btn').attr('disabled',true);}
}
); // < --- remove }
Check this working example:
https://codepen.io/nilestanner/pen/wqOaaO
I recommend that you use a IDE that has linting or error checking and this sort of issue will be easier to debug!
You had on extra '}'
$('#btn').prop("disabled", true);
$('#tc').on('click',function() {
if ($(this).is(':checked')) {
$('#btn').prop("disabled", false);
} else {
$('#btn').attr('disabled',true);
}
});
Try this
$("#btn").prop('disabled', true);//disable
$('#tc').click(function() {
if($(this).is(':checked'))
$("#btn").prop('disabled', true);//enable
else
$("#btn").prop('disabled', true);//disable
});
You have an extra ending bracket.
$('#btn').prop("disabled", true);
$('#tc').click(function() {
if ($(this).is(':checked')) {
$('#btn').prop("disabled", false);
} else {
$('#btn').attr('disabled',true);} // <--
}
});
I wish to disable a button in HTML on the condition that required fields are empty. The code given below is of the form in which the button is there:
<form>
Name*: <input type="text" size="20" name="name" /> <br /><br /> Surname: <input type="text" size="20" name="sur_name" /> <br />
<br /><br /> Mobile number: <input type="tel" size="15" name="mob" /> <br /><br /> E-mail id*: <input type="Email" size="30" name="user_id" /> <br /><br /> Password*: <input type="Password" size="30" name="pw1" /> <br /><br /> Confirm Password*: <input
type="password" size="30" name="pw2" /> <br /><br /><br /><br /> I accept the terms and conditions <input type="checkbox" name="t&c" /><br /><br />
<input type="submit" class="btn btn-lg btn-primary" value="Sign up now" onclick=window.location.href="https://www.google.co.in/signup" />
</form>
The form is actually a dummy sign up screen, yet the screen redirected is a 404 error screen, but I want the button to be disabled if certain fields are empty, and that it reloads the page if the two values for password are different.
I don't know JS completely, so please edit the code so that the parameters are clear.
Replace <input type="text" size="20" name="name" /> with <input type="text" size="20" name="name" required/>
Replace <input type="Email" size="30" name="user_id" /> with <input type="Email" size="30" name="user_id" required/>
Replace <input type="Password" size="30" name="pw1" /> with <input type="Password" size="30" name="pw1" required/>
Replace <input type="password" size="30" name="pw2" /> with <input type="password" size="30" name="pw2" required/>
I need to validate my form using jQuery or JavaScript when the page is submitted.
The conditions to validate my form are:
Name, age, and email of first passenger is compulsory.
If user enters additional names of any 2 to 10 passengers list then it should be mandatory to add age and email IDs of additional passengers.
Email IDs of all passengers should be unique and valid.
The user should agree to the terms and conditions.
Here's my HTML.
<form>
<div>
<input type="text" id="fn1" placeholder="Full Name" />
<input type="number" id="ag1" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em1" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn2" placeholder="Full Name" />
<input type="number" id="ag2" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em2" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn3" placeholder="Full Name" />
<input type="number" id="ag3" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em3" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn4" placeholder="Full Name" />
<input type="number" id="ag4" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em4" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn5" placeholder="Full Name" />
<input type="number" id="ag5" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em5" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn6" placeholder="Full Name" />
<input type="number" id="ag6" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em6" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn7" placeholder="Full Name" />
<input type="number" id="ag7" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em7" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn8" placeholder="Full Name" />
<input type="number" id="ag8" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em8" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn9" placeholder="Full Name" />
<input type="number" id="ag9" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em9" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn10" placeholder="Full Name" />
<input type="number" id="ag10" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em10" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<input type="checkbox" value="Agree to our terms and agreement" />
<input type="submit" value="submit" />
</form>
if ($('#fn1').val() == ""{
event.preventDefault();
$('#fn1').focus();
return
}
if ($('#fn1').val() != "" && ($('#ag1').val() == "" || !emailpattern.test($('#em1').val()))) {
event.preventDefault();
$('#fn1').focus();
return
}
I did this individually for every passenger. I have no code to check unique email IDs.
We can restate the four requirements as follows:
At least one name must be entered.
For each name that has been entered, the age and email address must be specified.
There must be a unique email address for each name.
The "terms and conditions" checkbox must be checked.
The snippet below validates all of these requirements. Note the following.
The HTML contains a single entry which is duplicated when the page loads. The global variable numEntries specifies the desired number of entries in the form.
We use entryCount to keep track of how many names have been entered into the form.
A hash is used to store the name corresponding to each email address. We look up each new email address in this hash to see if a name has already been assigned.
var numEntries = 10;
// Remove whitespace from beginning and end of string.
function strip(s) {
return s.replace(/^\s+|\s+$/, '');
}
window.onload = function () {
// Make ten entries and store them in an array.
var form = document.getElementById('entryForm'),
entry = form.getElementsByTagName('div')[0],
nextSibling = entry.nextSibling,
entries = [entry];
for (var i = 1; i < numEntries; ++i) {
var newEntry = entry.cloneNode(true);
form.insertBefore(newEntry, nextSibling);
entries.push(newEntry);
entry = newEntry;
}
// Make it easy to look up field values for each entry.
entries.forEach(function (entry) {
['name', 'age', 'email', 'phone'].forEach(function (field) {
entry[field] = entry.getElementsByClassName(field)[0];
});
});
// Attach a validation function to the form submission button.
document.getElementById('submitButton').onclick = function () {
if (!document.getElementById('agreementBox').checked) {
alert('Error: you must agree to our terms and conditions.');
return;
}
var entryCount = 0,
emailHash = {};
for (var i = 0; i < numEntries; ++i) {
var entry = entries[i],
name = strip(entry.name.value);
if (strip(entry.name.value) !== '') {
var age = strip(entry.age.value),
email = strip(entry.email.value);
if (age === '' || email === '') {
alert('Error: you must enter the age and email address of ' + name + '.');
return;
}
if (emailHash[email] !== undefined) {
alert('Error: ' + name + ' has the same email address as ' +
emailHash[email] + '. Addresses must be unique.');
return;
}
emailHash[email] = name;
++entryCount;
}
}
if (entryCount == 0) {
alert('Error: you must enter at least one name.');
return;
}
alert('Success! The form has been validated.');
};
};
.agreement {
font-family: sans-serif;
font-size: 12px;
}
<form id="entryForm">
<div>
<input class="name" type="text" placeholder="Full Name" />
<input class="age" type="number" placeholder="Age" />
<select>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input class="email" type="email" placeholder="E-mail" />
<input class="phone" type="number" placeholder="Mobile" />
</div>
<p class="agreement">
<input id="agreementBox" type="checkbox"> Agree to our terms and conditions
</p>
<input id="submitButton" type="submit" value="submit" />
</form>
Below is a version that uses exactly the HTML you posted in your question.
// Remove whitespace from beginning and end of string.
function strip(s) {
return s.replace(/^\s+|\s+$/, '');
}
window.onload = function () {
// Find the entry input areas and store them in an array.
var form = document.getElementsByTagName('form')[0];
var entries = form.getElementsByTagName('div');
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i],
inputs = entry.getElementsByTagName('input');
// Make it easy to look up field values for each entry.
['name', 'age', 'email', 'phone'].forEach(function (field, ix) {
entry[field] = inputs[ix];
});
}
// Attach a validation function to the form submission button.
var inputs = form.getElementsByTagName('input'),
agreementBox = inputs[inputs.length - 2],
submitButton = inputs[inputs.length - 1];
submitButton.onclick = function () {
if (!agreementBox.checked) {
alert('Error: you must agree to our terms and conditions.');
return;
}
var entryCount = 0,
emailHash = {};
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i],
name = strip(entry.name.value);
if (strip(entry.name.value) !== '') {
var age = strip(entry.age.value),
email = strip(entry.email.value);
if (age === '' || email === '') {
alert('Error: you must enter the age and email address of ' + name + '.');
return;
}
if (emailHash[email] !== undefined) {
alert('Error: ' + name + ' has the same email address as ' +
emailHash[email] + '. Addresses must be unique.');
return;
}
emailHash[email] = name;
++entryCount;
}
}
if (entryCount == 0) {
alert('Error: you must enter at least one name.');
return;
}
alert('Success! The form has been validated.');
};
};
form {
font-family: sans-serif;
font-size: 12px;
}
<form>
<div>
<input type="text" id="fn1" placeholder="Full Name" />
<input type="number" id="ag1" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em1" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn2" placeholder="Full Name" />
<input type="number" id="ag2" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em2" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn3" placeholder="Full Name" />
<input type="number" id="ag3" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em3" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn4" placeholder="Full Name" />
<input type="number" id="ag4" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em4" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn5" placeholder="Full Name" />
<input type="number" id="ag5" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em5" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn6" placeholder="Full Name" />
<input type="number" id="ag6" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em6" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn7" placeholder="Full Name" />
<input type="number" id="ag7" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em7" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn8" placeholder="Full Name" />
<input type="number" id="ag8" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em8" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn9" placeholder="Full Name" />
<input type="number" id="ag9" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em9" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<div>
<input type="text" id="fn10" placeholder="Full Name" />
<input type="number" id="ag10" placeholder="Age" />
<select><option value="Male">Male</option><option value="Female">Female</option></select>
<input type="email" id="em10" placeholder="E-mail" />
<input type="number" placeholder="Mobile" />
</div>
<input type="checkbox" value="Agree to our terms and agreement" />
<input type="submit" value="submit" />
</form>
I am kind of new to JQuery and Javascript and need your help on what I am missing here. I know the code works in jsfiddle.net but when I actually run it on my computer it's not doing anything. I want to keep the Object Oriented functions in "updated-formcheck.js" file separately.
I have a form validation HTML file with a jQuery function that calls my "updated-formcheck.js" file that checks all the empty fields and returns a msg. But when a submit button is clicked, nothing happens. Can you tell me why?
HTML file:
<script src="updated-formcheck.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
validateNow(e);
});
});
</script>
In "updated-formcheck.js" file:
function validateNow(eventObj){
var isValid = true;
$('input[type="text"].required, textarea.required, select.required').each(function() {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false) {
eventObj.preventDefault();
alert(this.e);
}else
this.s;
}
Because
$('input[type="text"].required, textarea.required, select.required')
in your code currently return an empty array, so each function is not called.
This is because you are looking for dom elements with a css class "required" that you doesn't have.
To get your code working I added a "required" class, which your js code is looking for, on the city element. I also updated the jQuery bind event to the form submit instead of a button click.
<html>
<head>
</head>
<body>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" class="required" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="updated-formcheck.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myform').on('submit', function(e) {
//e.preventDefault();
validateNow(e);
return false;
});
});
</script>
</body>
</html>
I'm using a JavaScript validator from http://www.javascript-coder.com/html-form/javascript-form-validation.phtml. The problem I'm facing is that I have one button that saves the registration (here I need to check for name and last name) and the second button which checks the entire form. However, if I press any button, it checks the entire form.
<form id="ministerial" name="register" action="" method="post">
<label>Title: </label>
<input type="text" name="title" value="" />
<label>First Name: </label>
<input type="text" name="first_name" value="" />
<label>Last Name: </label>
<input type="text" name="last_name" value="" />
<label>Organization: </label>
<input type="text" name="organization" value="" />
...
<input type="submit" name="save" value="SAVE REGISTRATION" />
<input type="submit" name="submit" value="SUBMIT REGISTRATION" />
</form>
<script type="text/javascript">
var frmvalidator = new Validator("ministerial");
frmvalidator.addValidation("title","req","Please enter a title");
frmvalidator.addValidation("first_name","req","Please enter the first name");
frmvalidator.addValidation("last_name","req","Please enter the last name");
frmvalidator.addValidation("organization","req","Please enter the organization");
</script>
Maybe this will work. Add validation for proper input fields onClick:
<form id="ministerial" name="register" action="" method="post">
<label>Title: </label>
<input type="text" name="title" value="" />
<label>First Name: </label>
<input type="text" name="first_name" value="" />
<label>Last Name: </label>
<input type="text" name="last_name" value="" />
<label>Organization: </label>
<input type="text" name="organization" value="" />
...
<input type="submit" name="save" value="SAVE REGISTRATION" onclick="return btnSave_click();" />
<input type="submit" name="submit" value="SUBMIT REGISTRATION" onclick="return btnRegister_click();" />
</form>
<script type="text/javascript">
var frmvalidator = new Validator("ministerial");
function btnSave_click(){
frmvalidator.clearAllValidations();
frmvalidator.addValidation("first_name","req","Please enter the first name");
frmvalidator.addValidation("last_name","req","Please enter the last name");
return true;
}
function btnRegister_click(){
frmvalidator.clearAllValidations();
frmvalidator.addValidation("title","req","Please enter a title");
frmvalidator.addValidation("organization","req","Please enter the organization");
return true;
}
</script>
I guess you will need to write a custom validation function