Radio button validation using JavaScript - javascript

This is my form
Select Staff : <select name="Staff" id="Staff"><br />
<option value="Staff">Select Staff</option>
The validation for the form is as simple this
<script type="text/javascript" language="javascript">
function validateMyForm ( ) {
var isValid = true;
if ( document.form1.Name.value == "" ) {
alert ( "Please type your Name" );
isValid = false;
} else if ( document.form1.Staff.value == "Staff" ) {
alert ( "Please choose Staff" );
isValid = false;
}
return isValid;
}
</script>
How do I validate radio buttons using JS ?

<input type="radio" name="question" id="question_yes" value="Yes" />Yes<br>
<input type="radio" name="question" id="question_no" value="No" />No
<script>
if(document.getElementById('question_yes').checked) {
// yes is checked
}else if(document.getElementById('question_no').checked) {
// no is checked
}
</script>
Here's a jsFiddle to show you how it works: http://jsfiddle.net/A3fg8/

Related

Javascript Multiple Alert Boxes

I created a little register form in HTML.
And I created a JS that pops up an alert for each of them if any of them are left blank
Now I want to combine all the alerts into a single one for example at the start a box will appear with all alerts and if you complete one if you push submit the next box will appear without the alert of the box you already completed
This is my JS Code:
function validate()
{
if( document.inrValid.Nume.value == "" )
{
alert( "Introduceti va rog numele!" );
document.inrValid.Nume.focus() ;
return false;
}
if( document.inrValid.Prenume.value == "" )
{
alert( "Introduceti va rog Prenumele!" );
document.inrValid.Prenume.focus() ;
return false;
}
if( document.inrValid.EMail.value == "" )
{
alert( "Introduceti va rog Emailul!" );
document.inrValid.EMail.focus() ;
return false;
}
if( document.inrValid.Telefon.value == "" )
{
alert( "Introduceti va rog Numarul de Telefon!" );
document.inrValid.Telefon.focus() ;
return false;
}
if( document.inrValid.parola.value == "" )
{
alert( "Introduceti va rog Parola!" );
document.inrValid.parola.focus() ;
return false;
}
return( true );
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="inrValid" onsubmit="return(validate());">
<p>Nume <input type="text" name="Nume" /></p>
<p>Prenume <input type="text" name="Prenume" /></p>
<p>EMail <input type="text" name="EMail" /></p>
<p>Telefon <input type="number" name="Telefon" /></p>
<p>Parola <input type="password" name="parola" /></p>
<p><input type="submit" onclick="clickAlert()" value="Submit" name="clickAlert" /></p>
</form>
<script src="script.js"> </script>
</body>
</html
As stated in the comment, you could use the required attribute as a small form of validation.
You could also add all of your error messages to an array, for example:
var checkForm = function () {
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var errors = [];
if (foo.value.length === 0) {
errors.push('Foo is blank');
}
if (bar.value.length === 0) {
errors.push('Bar is blank');
}
alert(errors.join(','));
};
<form onsubmit="checkForm()">
<input id="foo" type="text" />
<input id="bar" type="text" />
<input type="submit" />
</form>

The alert statements in the javascript do not show up?

The following javacript is used for validation checking. However the alert
statements do not appear when there is missing input.
I tried to delete the if statement and use only the alert statement and the
script works fine.
Is there anything wrong with the if statements?
Below is my HTML code:
<html>
<head>
<title>A More Complex Form with JavaScript Validation</title>
<script type="text/javascript">
// Validation form
function validate_form()
{
valid = true;
// check for missing name
if ( document.contact_form.contact_name.value == "" )
{
alert("Please fill in the 'Your Name' box,");
valid = false;
}
// check for missing gender
if ( document.contact_form.gender[0].checked == false ) && (
document.contact_form.gender[1].checked == false )
{
alert("Please choose your Gender: Male or Female");
valid = false;
}
// check for missing age
if ( document.contact_form.age.selectedIndex == 0 )
{
alert("Please select your Age.");
valid = false;
}
// check for missing terms
if ( document.contact_form.terms == false )
{
alert("Please check the Terms & Conditions box.");
valid = false;
}
return valid;
}
//-->
</script>
</head>
<body>
<h1>Please Enter Your Details Below</h1>
<form name="contact_form" onsubmit="validate_form()">
<p>Your Name:
<input type="text" name="contact_name" size="20">
</p>
<p>
Your Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>
Your Age:
<select name="age">
<option value="1">0-14 years</option>
<option value="2">15-30 years</option>
<option value="3">31-44 years</option>
<option value="4">45-60 years</option>
<option value="5">61-74 years</option>
<option value="6">75-90 years</option>
</select>
</p>
<p>
Do you agree to the Terms and Conditions?
<input type="checkbox" name="terms" value="yes">Yes
</p>
<input type="submit" name="submit" value="Send Details">
</form>
</body>
</html>
if ( document.contact_form.gender[0].checked == false ) && (
document.contact_form.gender[1].checked == false )
{
alert("Please choose your Gender: Male or Female");
valid = false;
}
you have to change if condition like that
if ( document.contact_form.gender[0].checked == false &&
document.contact_form.gender[1].checked == false )
{
alert("Please choose your Gender: Male or Female");
valid = false;
}
Your script can't fire up because of this mistake.
Tip: You can check script errors from dev-console of browsers like Chrome Console.
as "trincot" said by comment, you can also use ! operator to check boolean values like that.
if ( !document.contact_form.gender[0].checked && !document.contact_form.gender[1].checked )
{
alert("Please choose your Gender: Male or Female");
valid = false;
}

inserting audio in radio button html

This is the code for playing an audio when a radio button is clicked and evaluated by a Submit button.
There are two sound files separately for two radio buttons respectively. These files are not playing when they are evaluated by a Submit button. Please check out that whether the code works properly or not.
<html>
<head>
<script LANGUAGE="JavaScript">
var snd = new Audio('\Users\raja\Desktop\abs.mp3');
var x = new Audio('\Users\raja\Desktop\new.mp3');
function ValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if ( ( form.gender[0].checked == true ) && ( form.gender[1].checked == false ) )
{
snd.play();
alert ( "Your Gender:Male");
return false;
}
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == true ) )
{
x.play();
alert ( "Your Gender:Female");
return false;
}
if (ErrorText= "") { form.submit() }
}
</script>
</head>
<body>
<form name="feedback" action="#" method=post>
Your Gender:
<p><input type="radio" name="gender" value="Male"> Male </p>
<p><input type="radio" name="gender" value="Female" > Female</p>
<input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>

Validation for radio button using javascript

I have 2 radio buttons. I need to give validations for radio button using javascript. Please tel me whats wrong with my code. Here is the code.
$(function() {
$("#XISubmit").click(function(){
var XIGender= document.forms["XIForm"]["XIGender"].value;
if (XIGender==null || XIGender=="") {
alert("Please select the gender");
return false;
}
document.getElementById("XIForm").submit();
});
Here is my HTML code:
<label>Gender </label> &nbsp&nbsp
<input type='radio' name='XIGender' value='Male' id="XImale"/>Male
<input type='radio' name='XIGender' value='Female' id="XIfemale"/>Female</td>
One more here,
$(document).ready(function() {
$("#XISubmit").click(function () {
if($('input[name=XIGender]:checked').length<=0){
alert("Please select the gender");
return false;
}
$( "#XIForm" ).submit();
});
});
JSFiddle
Here is the code. You will have to create a form and validate it on submit.
HTML:-
<form name="myForm" action="targetpage.asp" onsubmit="return validateForm();" method="post">
<label>Gender</label>&nbsp&nbsp
<input type='radio' name='XIGender' value='Male' id="XImale" />Male
<input type='radio' name='XIGender' value='Female' id="XIfemale" />Female</td>
<input type="submit" value="submit" id="XISubmit" />
</form>
JS:-
function validateForm() {
if (validateRadio(document.forms["myForm"]["XIGender"])) {
alert('All good!');
return false;
}
else {
alert('Please select a value.');
return false;
}
}
function validateRadio(radios) {
for (i = 0; i < radios.length; ++i) {
if (radios[i].checked) return true;
}
return false;
}
Hope this will help you. :)
Enjoy coding.
<form name="formreg" enctype="multipart/form-data" method="post">
<input type="radio" value="male" name="gender" /> Male<br />
<input type="radio" value="female" name="gender" /> Female<br />
<input value="Submit" onclick="return inputval()" type="submit" />
</form>
JS:
<script type="text/javascript">
function inputval() {
var $XIForm = $('form[name=XIForm]');
if ($("form[name='formreg'] input[type='radio']:checked").length != 1) {
alert("Select at least male or female.");
return false;
}
else {
var gender = $("input").val();
//alert(gender);
$XIForm.submit();
alert(gender);
}
}
</script>
You can't get the value of the radio button like that. document.forms["XIForm"]["XIGender"] will return more than one node and you can't get the value property of a list of nodes. Since your using jQuery, this can be made much easier:
$("#XISubmit").click(function () {
var $XIForm = $('form[name=XIForm]');
var XIGender = $XIForm.find('input[name=XIGender]:checked').val();
if (XIGender == null || XIGender == "") {
alert("Please select the gender");
return false;
}
$XIForm.submit();
});
JSFiddle
Use the :checked selector as below
function() {
var len = $("input:checked").length;
if(len == 0) {
alert("Please select a gender");
return false;
}
see fiddle

Javascript won't validate my dropdown

I'm having small trouble with javascript validation. I need to validate the select dropdown in my form. I can validate all fields so far but somehow I cannot validate the select dropdown list? Can someone help me validate my form?
Here is my javascript:
<script type="text/javascript">
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}
}
}
function validate()
{
//username password First_n Last_n Company Mobile Email Residence
if( document.form1.First_n.value == "" )
{
alert( "Please enter your first name!" );
document.form1.First_n.focus() ;
return false;
}
if( document.form1.Last_n.value == "" )
{
alert( "Please enter your last name!" );
document.form1.Last_n.focus() ;
return false;
}
if( document.form1.username.value == "" )
{
alert( "Please enter your username!" );
document.form1.username.focus() ;
return false;
}
if( document.form1.password.value == "" )
{
alert( "Please enter your password!" );
document.form1.password.focus() ;
return false;
}
if( document.form1.Mobile.value == "" )
{
alert( "Please provide us your mobile number!" );
document.form1.Mobile.focus() ;
return false;
}
if( document.form1.Email.value == "" )
{
alert( "Please provide us your Email!" );
document.form1.Email.focus() ;
return false;
}
var yourSelect = document.getElementById('Residence');
alert(yourSelect.options[yourSelect.selectedIndex].value)
if(yourSelect.options[yourSelect.selectedIndex].value == '' )
{
alert( "Please provide your country!" );
return false;
}
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}
}
return( true );
}
</script>
And my form:
<form name="form1" method="post" action="add_new.php" onsubmit="return(validate(false));">
<div style="clear:both;padding:0px 10px 0 10px;margin-bottom:40px;">
<h5>Interested in</h5>
<input id="toggle-on" class="toggle toggle-left" name="toggle" value="Hosting" type="radio" checked>
<label for="toggle-on" class="btn">Hosting</label>
<input id="toggle-off" class="toggle toggle-right" name="toggle" value="Email accounts" type="radio"
><label for="toggle-off" class="btn">Email accounts</label>
</div>
<div style="clear-both;">
<input name="First_n" type="text" placeholder="First Name*" class="login-text-lbl-pink-no-width" id="First_n">
<input name="Last_n" type="text" placeholder="Last Name*" class="login-text-lbl-pink-no-width" id="Last_n">
</div>
<input name="username" type="text" placeholder="Username*" class="login-text-lbl-pink-no-width" id="username"><br/>
<input name="password" type="password" placeholder="Password*" class="login-text-lbl-pink-no-width" id="password"><br/>
<input name="Company" type="text" placeholder="Company" class="login-text-lbl-pink-odd" id="Company"> <br/>
<input name="Mobile" type="text" placeholder="Phone Number*" class="pink-transparent-item" id="Mobile"> <br/>
<input name="Email" type="text" placeholder="Email*" class="login-text-lbl-pink-odd" id="Email"> <br/>
<select name="Residence" id="Residence" style="background-color: rgba(240, 96, 96, 0.62);border: none;-webkit-appearance: none;
-moz-appearance: none;appearance: none;height: 40px;font-style: italic;width: 270px;padding: 10px;margin: 5px;color: #552726;border-radius: 5px;border: none;float: left;" class="required">
<option value="zero" selected>Country*</option>
<option value="US">America</option>
<option value="DE">Germany</option>
<option value="IT">Italy</option>
<option value="HK">Hong Kong</option><br/>
<input name="domain" class="login-text-lbl-pink-odd" type="text" style="width:350px;margin-bottom:40px;" placeholder="Existing domain" id="domain"> <br/>
<input type="submit" name="Submit" value="Submit" style='font-family: "Neo Sans Light", Verdana, Tahoma;' class="login-button-pink">
</form>
I believe the problem is in the email validation that happens just before the country validation, because if an email address is entered it returns from the function regardless of whether the email passed validation, so it never gets to the country bit:
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}else
return true; // delete this line, and the else
}
You want to return false if there's a problem, but you don't want to return true until the end of the function.
UPDATE: The code now shown in the updated question doesn't work because:
You deleted the validateEmail() function declaration (replacing it with a copy of the code I said to change at the end of validate() - unless that was just a weird copy/paste error in the question)
You changed the if test on the country to check for an empty string, but didn't update the corresponding value="zero" to be value=""
If you fix those it works as shown here: http://jsfiddle.net/58A7K/
Note also that the code I showed above can be simplified - you don't need the ret variable:
if( document.form1.Email.value != "" ) {
if (!validateEmail(document.form1.Email)) {
return false;
}
}
The problem is with following code:
if( document.form1.Email.value != "" )
{
// Put extra check for data format
var ret = validateEmail(document.form1.Email);
if( ret == false )
{
return false;
}else
return true;
}
In the above code, when user enters a valid email, your are returning TRUE as a result the code for validating country is never executed.
Remove the else part from above code snippet.

Categories

Resources