edit: I don't think the similar question mentinoed in the comments can help :(. Unless I'm just really bad at this... I can get a simple alert message to come up but can't get the alert for the the individual radio button to show.
I'm just doing a simple form with radio buttons with Javascript to give an alert after hitting submit when one of the choices is chosen. I'm brand new to Javascript so I'm not sure what else I can do...
The HTML works but the function inside of it doesn't at all. I'm lost on what else to do. Any advice would be really appreciated.
<!DOCTYPE html>
<html>
<head>
<title> Gender Check </title>
<meta charset ="UTF-8">
</head>
<body>
<form id= "form" name ="form" onsubmite="gender()">
<label>Male
<input type="radio" id="male" name="male"/>
</label>
<label>Female
<input type="radio" id="female" name="female"/>
</label>
<label>Trans
<input type="radio" id="trans" name="trans"/>
</label>
<label>Alien
<input type="radio" id="alien" name="alien"/>
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="helicopter"/>
</label>
<input type="submit" name="submit" value="Don't lie to me."/>
</form>
<script type="text/javascript">
function gender() {
var male=document.form[0].element[0];
var female=document.form[0].element[1];
var trans=document.form[0].element[2];
var alien=document.form[0].element[3];
var helicopter=document.form[0].element[4];
if (document.getElementById('male').checked == true)
{
alert("You are a Male.")
}
else if (document.getElementById('female').checked == true)
{
alert("You are a Feale.")
}
else if (document.getElementById('trans').checked == true)
{
alert("You are Trans.")
}
else if (document.getElementById('alien').checked == true)
{
alert("You are an...uh...Alien?")
}
else if (document.getElementById('helicopter').checked == true)
{
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
}
else
{
alert("Please pick a choice")
}
}
document.forms[0].onsubmit = gender;
</script>
</body>
</html>
The errors were :
You used document.form[0].element[1] instead of document.form[1]
You wrote onsubmite instead of onsubmit
All your radio input had the same name attribute thus you were able to select multiple choices. You should use the same name for each radio button of the same group
You can reduce male.checked == true with male.checked alone
function gender() {
var male = document.form[0];
var female = document.form[1];
var trans = document.form[2];
var alien = document.form[3];
var helicopter = document.form[4];
if (male.checked) {
alert("You are a Male.")
} else if (female.checked) {
alert("You are a Female.")
} else if (trans.checked) {
alert("You are Trans.")
} else if (alien.checked) {
alert("You are an...uh...Alien?")
} else if (helicopter.checked) {
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
} else {
alert("Please pick a choice")
}
}
<!DOCTYPE html>
<html>
<head>
<title>Gender Check</title>
<meta charset="UTF-8">
</head>
<body>
<form id="form" name="form" onsubmit="gender()">
<label>Male
<input type="radio" id="male" name="choice" />
</label>
<label>Female
<input type="radio" id="female" name="choice" />
</label>
<label>Trans
<input type="radio" id="trans" name="choice" />
</label>
<label>Alien
<input type="radio" id="alien" name="choice" />
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="choice" />
</label>
<input type="submit" name="submit" value="Don't lie to me." />
</form>
</body>
</html>
NOTE
Instead of document.form[0]; (first element of the form) you can use document.form.choice[0] which will look for the list of radio and select the first one [0]
<form id= "form" name ="form" onsubmit="gender()">
You need to associate an event known as onsubmit which will call gender() function when form is submitted.
You can prevent the submission by returning false via function and for that you will need to do something like this
onsubmit="return gender()"
If you want to submit form, change the button type to button and associate an event as onclick='gender()' and keep rest of the code unchanged.
Related
I need help to validate a form on submit. It should check that one of more checkboxes are selected or else display error message. I have currently got it working but the problem is the checkbox option is displayed after selecting a radio button on the form.
The code I have now still shows an error message even if the div isn't displayed which is a big issue as users haven't seen the checkbox option.
I want the checkbox error message to show ONLY if the user has selected the radio button "NO" and therefor is required to check a checkbox. If they select the radio button "YES" and this checkbox div is not displayed, then I don't want the error message on submit.
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
function validateForm() {
var checked = false;
var elements = document.getElementsByName("tick");
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
if (!checked) {
alert('You must select why you are attending!');
}
return checked;
}
<form id="form" method="post" enctype="text/plain" name="vform">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" name="submit" onclick="validateForm()" value="send">Submit</button>
</div>
</form>
try (select "No" below)
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
// DISPLAY HIDDEN TEXT
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
<form id="form" method="post" enctype="text/plain" name="form">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" onclick="validateForm(event)" name="submit" value="send">Submit</button>
</div>
</form>
Here's the old school way. Just check the display attribute of the div, and only set your flag to false inside that.
function validateForm() {
var checked;
if(document.getElementById("hidden").style.display == "block") {
checked = false;
var elements = document.getElementsByName("tick");
for (var i=0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
}
if (checked===false) {
alert('You must select why you are attending!');
}
return checked;
}
I am trying to change text in html using the DOM. I have a form with 2 radio buttons and a submit button. When submitted, it runs a JS function that should change text in HTML to reflect what answer they chose. However, whenever you click the submit button, it changes the text and then instantly flickers back to what the html shows. Why is it doing this? I've never seen this before. Here is the code...
function answerNext()
{
if(document.getElementById("question1").checked == true)
{
document.getElementById("qtext").innerText="You chose the first option";
}else if (document.getElementById("question2").checked == true)
{
documet.getElementById("qtext").innerText="You chose the second option";
}else
{
document.getElementById("qtext").innerText="You chose neither option";
document.getElementById("testdiv").innerHTML="<h1>You clicked next</h1>";
}
}
<!doctype html>
<html>
<head>
<title>Dog Personailty Quiz</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/script.js"></script>
</head>
<body>
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<input type="radio" id="question1" value="option1"> Option 1
<input type="radio" id="question2" value="option1"> Option 2
<input type="submit" value="Next" onclick="answerNext();">
</form>
</body>
</html>
First of all, you could change the input's attribute type to "button" but if you wish to keep it as a submit button you'll need to stop the forms submit event to prevent the page navigating away/refreshing.
You do this by using the first argument of the event's function. The first argument holds the event that was triggered. If the browser doesn't support this, there is a fallback using window.event (we are checking this first because some browsers only support the argument and some only the window.event).
Stop browser from triggering the submit event using this example:
function answerNext(evt)
{
if (evt == null)
{
evt = window.event;
}
evt.preventDefault();
evt.stopPropagation();
. . .
Secondly, you'll want to group the ratio inputs so only one can be selected at a time. Do this by creating a fieldset element and adding the name attribute to the inputs, connecting them to that group:
<fieldset id="group1">
<input type="radio" id="question1" value="option1" name="group1"> Option 1
<input type="radio" id="question2" value="option2" name="group1"> Option 2
</fieldset>
Also, there was an error in the if else statement where there's a typo documet should be document.
Try out this code I've fixed for you:
function answerNext(evt)
{
if (evt == null)
{
evt = window.event;
}
evt.preventDefault();
evt.stopPropagation();
if(document.getElementById("question1").checked == true)
{
document.getElementById("qtext").innerText="You chose the first option";
}else if (document.getElementById("question2").checked == true)
{
document.getElementById("qtext").innerText="You chose the second option";
}else
{
document.getElementById("qtext").innerText="You chose neither option";
document.getElementById("testdiv").innerHTML="<h1>You clicked next</h1>";
}
}
fieldset#group1
{
border: none;
display: inline;
}
<!DOCTYPE html>
<html>
<head>
<title>Dog Personailty Quiz</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/script.js"></script>
</head>
<body>
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<fieldset id="group1">
<input type="radio" id="question1" value="option1" name="group1"> Option 1
<input type="radio" id="question2" value="option2" name="group1"> Option 2
</fieldset>
<input type="submit" value="Next" onclick="answerNext();">
</form>
</body>
</html>
Change your button type from submit to just button so the form doesn't actually submit.
<input type="button" value="Next" onclick="answerNext();">
You'll also want to fix the typo (documet) and implement a radio group to prevent both from being selected. Finally, wrap your radio buttons and their text in label elements for accessibility and better usability (the label text becomes clickable).
Demo of all that
function answerNext() {
if (document.getElementById("question1").checked == true) {
document.getElementById("qtext").innerText = "You chose the first option";
} else if (document.getElementById("question2").checked == true) {
document.getElementById("qtext").innerText = "You chose the second option";
} else {
document.getElementById("qtext").innerText = "You chose neither option";
document.getElementById("testdiv").innerHTML = "<h1>You clicked next</h1>";
}
}
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<label><input type="radio" id="question1" value="option1" name="blah"> Option 1</label>
<label><input type="radio" id="question2" value="option1" name="blah"> Option 2</label>
<input type="button" value="Next" onclick="answerNext(event);">
</form>
Please bear with me as I am a beginner when it comes to JavaScript !
I have a dymamic form that pulls information from a database. For each line in the database there is a new row of form fields and the select name incorporates the id from the database - this is all on the same form e.g
<select name="supplier<%=objRst.fields("returnpartid")%>" id="supplier<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="STOCKACTION<%=objRst.fields("returnpartid")%>" id="STOCKACTION<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="stockreason<%=objRst.fields("returnpartid")%>" id="stockreason<%=objRst.fields("returnpartid")%>">
<select name="creditaction<%=objRst.fields("returnpartid")%>" id="creditaction<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="rejectreason<%=objRst.fields("returnpartid")%>" id="rejectreason<%=objRst.fields("returnpartid")%>">
Users are currently missing out data when they are saving the record and I want to prevent this, The save button saves ALL of the records in one go so some lines will be totally blank if they have not yet been processed.
If a user has started to fill in the row but not completed all the information for that record then I need to stop the form submission.
Take a look at Parsley. I use this to validate my login and create user page of my website. Let me know what you think of it!
This is a great javascript tool that utilizes jQuery to validate different forms. Its really nice as you can have it validate several different things such as max and or min text length. It is very easy to implement because all you need to do is add the identifiers to the HTML element.
EDIT:
To avoid a link only answer, here is the code that could be helpful.
<form id="demo-form" data-parsley-validate>
<label for="question">Do you code? *</label>
<p>
<input type="radio" name="question" value="true" required /> Yes
<input type="radio" name="question" value="false" /> No
</p>
<label for="languages">If yes, in which language(s)?</label>
<input type="text" class="form-control" name="languages" data-parsley-conditionalrequired='[" [name=\"question1\"]:checked", "yes"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you are a programmer!" />
<label for="question">Do you eat dog food? *</label>
<p>
<input type="radio" name="question2" value="yes" required /> Yes
<input type="radio" name="question2" value="no" /> No
</p>
<label for="why">If no, why?</label>
<input type="text" class="form-control" name="why" data-parsley-conditionalrequired='[" [name=\"question2\"]:checked", "no"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you do not eat dog food!" />
<input type="submit" class="btn btn-default pull-right" />
</form>
<script type="text/javascript">
window.ParsleyConfig = {
validators: {
conditionalrequired: {
fn: function (value, requirements) {
// if requirements[0] value does not meet requirements[1] expectation, field is required
if (requirements[1] == $(requirements[0]).val() && '' == value)
return false;
return true;
},
priority: 32
}
}
};
</script>
<script type="text/javascript" src="../../dist/parsley.js"></script>
EDIT 2:
This is also a simple html file that could do something close to what I think that you want:
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<input id="test" type="checkbox" id="chk"/>asdfad
<form>
<textarea></textarea>
<button onclick="myFunction()">asd</button>
<form>
<p>If the check box is check the thing is required and if the box is not check then it is not required. So tell your form to only save the rows that have the box checked?</p>
<script>
function myFunction() {
if(document.getElementById("test").checked){
document.getElementsByTagName("textarea")[0].setAttribute("required", "true");
}
else{
document.getElementsByTagName("textarea")[0].removeAttribute("required");
}
}
</script>
</body>
</html>
How to make radio button change the form action address
I got a form which have the following
and a radio button
<b>Would you like to to make payment ? <input type="radio" name="choice" value="yes">Yes <input type="radio" name="choice" value="no" checked>No</b>'
If user selection is no (default checked) the form action will still be register_page4.php
but if user selected yes and press the submit button:
<input id="btnSubmit" type="submit" value="Next" />
I would like the form action to be payment.php instead of register_page4.php, how do I achieve it.
I make the changes and this is what I type
<html>
<head>
</head>
<body>
<form name="form1" method="post" action="register_page4.php">
Would you like to make an appointment for collection ?
<input type="radio" name="collection" value="yes">Yes
<input type="radio" name="collection" value="no" checked>No
<input id="btnSubmit" type="submit" value="Next" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
jQuery(document).ready(function($) {
var form = $('form[name="form1"]'),
radio = $('input[name="choice"]'),
choice = '';
radio.change(function(e) {
choice = this.value;
if (choice === 'yes') {
form.attr('action', 'payment.php');
} else {
form.attr('action', 'register_page4.php');
}
});
});
</script>
</body>
</html>
But the result is still going to register_page4.php even I click on the radio button with yes, I try click on both and both still go to register_page4.php
Here is an example using a javascript solution. Basically, when changing the radio button, the attribute of the form (here with id #yourForm) is altered with the correct action.
jQuery(document).ready(function($) {
var form = $('form[name="form1"]'),
radio = $('input[name="collection"]'),
choice = '';
radio.change(function(e) {
choice = this.value;
if (choice === 'yes') {
form.attr('action', 'payment.php');
} else {
form.attr('action', 'register_page4.php');
}
});
});
depending on whether you are using POST or GET method, it's either:
$nextPage = ($_POST['choice']=='yes') ? 'payment.php' : 'register_page4.php';
OR
$nextPage = ($_GET['choice']=='yes') ? 'payment.php' : 'register_page4.php';
then simply redirect to $nextPage
$("input[name=choice]").change(function(){
if ($("input[name=choice]").val() == 'yes'){
$("#formId").attr("action","payment.php");
}
else
{
$("#formId").attr("action","register_page4.php");
}
});
Disable Submit button if checked = No
Working JSFiddle DEMO
HTML
<form action="payment.php" method="POST">
<input name="choice" type="radio" id="choiceyes" value="yes" />Yes
<input name="choice" type="radio" id="choiceno" value="no" checked="checked" />No
<input id="btnSubmit" name="btnSubmit" type="submit" value="Next" /></form>
Script
$(function () {
var $join = $("input[name=btnSubmit]");
var processJoin = function (element) {
if(element.id == "choiceno") {
$join.attr("disabled", "disabled");
}
else {
$join.removeAttr("disabled")
}
};
$(":radio[name=choice]").click(function () {
processJoin(this);
}).filter(":checked").each(function () {
processJoin(this);
});
});
Add Document Ready
<script>
$(document).ready(function(){
$("input[name=choice]").change(function(){
if ($("input[name=choice]").val() == 'yes'){
$("#form1").attr("action","payment.php");
}
else
{
$("#form1").attr("action","register_page4.php");
}
});
});
</script>
If continue the issue try to remove the action:
Remove action from form.
<form name="form1" method="post" action="register_page4.php">
Correct
<form name="form1" method="post">
Use the following code:
<body>
<form name="form1" id="form1" method="post" action="register_page4.php">
Would you like to make an appointment for collection ?
<input type="radio" name="collection" value="yes" onChange="if(this.checked){document.getElementById('form1').action='payment.php'}">Yes
<input type="radio" name="collection" value="no" checked>No
<input type="submit">
</form>
</body>
Here is a demo
I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks