Having Issue on Using Boolean With Simple Validation - javascript

Can you please take a look at This Demo and let me know why this bug is happening during the validation of two type of input selections?
Technically, what is happening is if user not select either of checkboxes and Select options and push the submit button the error message shows up and the validRequest boolean stays in false. Now if user ONLY select the checkboxes the situation is same the validRequest boolean is false and error message shows up BUT if user forgets to select the checkboxes and only selects from the list the validateQuery() validates the validRequest as True and then now error message and alert message pops up!
Can you please let me know why this is happening?
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
if ($(selectedDoll).is(':checked')) {
validRequest = true;
$('#err').html('');
} else {
validRequest = false;
$('#err').html('Some Thing Wrong!');
}
var selectedIcecream = $("#icecream").val();
if (selectedIcecream == 0) {
validRequest = false;
$('#err').html('Some Thing Wrong!');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
#err{color:red;}
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>

Fixed: http://jsfiddle.net/byk309j8/7/
The problem was that you had 2 independent if statements while you must have only one. Also you were checking if the select box is empty == 0 instead of not empty !== 0
$(function () {
var validRequest = false;
function validateQuery() {
var selectedDoll = $('input:checkbox[name=doll]');
var selectedIcecream = $("#icecream").val();
// checkbox is not checked, but select is
if ($(selectedDoll).is(':checked') && selectedIcecream == 0) {
validRequest = false;
$('#err').html('select not selected');
} else if ($(selectedDoll).is(':checked') == false && selectedIcecream != 0) {
validRequest = false;
$('#err').html('checkbox not checked');
} else if ($(selectedDoll).is(':checked') == false || selectedIcecream == 0) {
validRequest = false;
$('#err').html('checkbox not checked or select not selected');
} else {
validRequest = true;
$('#err').html('');
}
}
$("#isValid").on("click", function () {
validateQuery();
if(validRequest){ alert('Ready To Go');}
console.log(validRequest);
});
});
<div>
<input type="checkbox" name="doll" value="cat" />Cats
<br />
<input type="checkbox" name="doll" value="dog" />Dogs
<br />
<input type="checkbox" name="doll" value="bird" />Birds
<br />
<br />
<select id="icecream">
<option value="0">Select From List</option>
<option value="chocolate">Chocolate</option>
<option value="vanilla">Vanilla</option>
<option value="strawberry">Strawberry</option>
<option value="caramel">Caramel</option>
</select>
</div>
<p>
<input type="submit" id="isValid" value="Submit now" />
</p>
<p>
<div id="err"></div>
</p>
#err{color:red;}

Related

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

registration form validation using javascript

Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box -  should be in format example#gmail.com
Website : Text box -  should be in format http://www.example.com
Country : Select box with 10 countries
Mobile :  Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
//     $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>

Radio button validaton

I am trying to get a couple of radio buttons to validate using JavaScript/HTML, but I am having problems. The piece of script I am having trouble with is as follows -
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}
Basically I want it to return an alert if neither radio button options are selected. At the moment when submitted the form is refreshing itself and not providing any alerts. Any advice would be appreciated!
The relevant HTML I have been provided to work with is -
<form id="RegistrationForm" onsubmit="ValidateForm()" action="">
<fieldset>
<legend>Registration Form</legend>
<label for="username">User Name: </label>
<input type="text" class="input" id="username"/><br />
<label for="password">Password: </label>
<input type="password" class="input" id="password"/><br />
<label for="repassword">Re-Type Password: </label>
<input type="password" class="input" id="repassword"/><br />
<label for="email">Email Address: </label>
<input type="text" class="input" size="30" id="email"/><br />
<label>Age: </label>
<select id ="age" name="age">
<option value=""> --- </option>
<option value="0-18">0-18</option>
<option value="18-30">18-30</option>
<option value="30-50">30-50</option>
<option value="50+">50+</option>
</select><br/>
<label for="sexm">Sex:</label>
<input type="radio" id="sexm" name="sex" value="male" />Male<br/>
<label for="sexf"> </label>
<input type="radio" id="sexf" name="sex" value="female" />Female<br/>
<input type="checkbox" name="agree" id="agree" value="agree"/>
<label for="agree">I accept the terms and cond.</label> <br/>
<label> </label>
<input type="submit" value="Submit" class="button" />
</fieldset>
</form>
Try this code in your javascript <script> tag
function ValidateForm () {
if ( ( document.getElementById("sexm").checked == false ) && ( document.getElementById("sexm").checked == false ))
{
alert( "Please select your sex" );
return false;
} else {
return true;
}
}
Replace it with your code
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}
Use a for loop to check whether your user has selected any value or not, if not, than throw an alert and use return false to prevent your form being submitted.
Demo
var ischecked = null;
var radios = document.getElementsByName('sex');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
ischecked = radios[i];
}
}
if(ischecked==null) {
alert('Please choose your Sex');
return false;
}
Save the above code in the function, and call it on submit of your form.
Demo 2 (Validate on submit)
Note: You need to use onsubmit="return ValidateForm();"
try this ...
<script type="text/javascript">
function validate()
{
var o = document.getElementById('sexm');
var t = document.getElementById('sexf');
if ( (o.checked == false ) && (t.checked == false ) )
{
alert ("please select your sex" );
return false;
}
return true;
}
</script>

Jquery form validation not working no plugin used

I'm new to Jquery and came across something I can not solve think I need someone who with a little more experience.
Form validation is not working correctly but works fine on jsfiddle.
Am I suppose to have document.ready ?
Any help would be great thanks
<script>
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
</script>
<form action="add_film.php" method="post" id="add_film">
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating" name="rating"/>
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
You had not closed your form tag, so the script doesn't work.
Here is the working code for you.
http://jsbin.com/EDOJEZ/1/edit?html,output
Yes!!! the code should be in document ready handler
jQuery(function($){
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
// Focus on first form field.
$("input:text:visible:first").focus();
if (error) {
e.preventDefault();
}
});
})
you please run your web page in google chrome and press ctrl+shift+j to open developer console. So that you could see the javascript/jquery errors with line numbers+preview there and try to resolve yourself. I promise, you can do it as simple.

Validation of Dropdown list doesn't work

The following is the code for validating a form with radio buttons, text boxes and dropdown list. The javascript for validating radio buttons and textbox works. But the javascript for dropdown doesn't work. Can you tell me what is it that I've done wrong?
Please help!
Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var checked = null;
var name1 = document.forms["information"]["firstname"].value;
var n=name1.split(" ");
var name = n[0];
var sex = document.forms["information"]["sex"];
var e = document.getElementById("prof1");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(name == null || name== "")
{
alert('Enter First Name');
return false;
}
for (var i=0;i<2;i++)
{
if(sex[i].checked)
{
checked = sex[i];
return true;
}
}
if (checked == null)
{
alert(' Enter Sex');
return false;
}
if(strUser==0)
{
alert("Enter Profession");
return false;
}
}
</script>
</head>
<body>
<form name="information" onsubmit="return validateForm()" method="post">
<text style="color:red">*</text> First Name: <input type="text" name="firstname"><br><br>
Last Name: <input type="text" name="lastname"><br><br>
<text style="color:red">*</text> Sex: <input type="radio" name="sex" value="Male"> Male
<input type="radio" name="sex" value="Female"> Female <br><br>
<text style="color:red">*</text> Profession:
<select id="prof1">
<option value="0"> Select </option>
<option value="1"> Engineer </option>
<option value="2"> Doctor </option>
<option value= "3"> Lawyer </option>
<option value="4"> Others </option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
if(sex[i].checked)
{
checked = sex[i];
return true;
}
Remove return true above.
for ( var i = 0; i < 2; i++) {
if (sex[i].checked) {
checked = sex[i];
//return true;
}
}
Uncomment the return true;
The return statement inside the loop return the value and this results to non-execution of code written after this return statement.
2.
if(strUser==0)
replace with
if(strUser=="0")
Reason :
http://www.w3schools.com/jsref/prop_select_selectedindex.asp
http://www.w3schools.com/jsref/prop_option_value.asp

Categories