Javascript form validation checkbox and radio not working - javascript

I have a form that I need to validate with javascript to make sure at least one checkbox and one radio is checked. I know it would probably be easier to use jQuery but I'm trying to accomplish this with pure javascript. Here is the code:
<form name="bulbform" action="compute.php" onsubmit=" return validateForm()" method="post">
<p>Enter your name: <input type="text" name="name" size="20"></p>
<p><strong>Light Bulbs</strong></p>
<label><input type="checkbox" name="bulbs[]" value="2.39">Four 25-watt light bulbs for $2.39</label><br>
<label><input type="checkbox" name="bulbs[]" value="4.29">Eight 25-watt light bulbs for $4.29</label><br>
<label><input type="checkbox" name="bulbs[]" value="3.95">Four 25-watt long-life light bulbs $3.95</label><br>
<label><input type="checkbox" name="bulbs[]" value="7.49">Eight 25-watt long-life light bulbs $7.45</label><br>
<p><strong>Payment Method</strong></p>
<label><input type="radio" name="cc" value="Visa">Visa</label><br>
<label><input type="radio" name="cc" value="Master Card">Master Card</label><br>
<label><input type="radio" name="cc" value="Discover">Discover</label><br>
<p><input type="submit" value="Order" /> <input type="reset" value="Clear form"/></p></form>
Here is my javascript
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
alert(value);
return true;
}
else{
alert("You must select a payment method.")
return false;
}
With the else removed I'm able to show the credit card selected but when I add the else it always says you must select a payment method and is never true... Thanks ahead of time for any advice you can give.

See this plunker: https://plnkr.co/edit/5NiIA1w9axvmOJEjXVlP
function validateForm() {
var radios = document.getElementsByTagName('input');
var value;
var paymentMethodSelected = false;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
alert(value);
paymentMethodSelected = true;
}
}
if (!paymentMethodSelected) {
alert("You must select a payment method.");
return false;
}
return true;
}
You don't have an ending form tag (not critical, but good practice)
You were returning from the validation function before you had checked all radio buttons
The check for an invalid form state should be handled outside the for loop

The variable radios contains checkboxes, textbox, and radio buttons.
A radio button and a textbox are not checkbox.
So the condition radios[i].type=='radio' && radios.type='checked' will evaluate to false and the else part will be evaluated.
The code below uses the variables checkedCB and checkedRadio to store if any checkbox or radio button is checked.
Try something like this:
function validateForm() {
var inputs = document.getElementsByTagName('input');
var valued;
var checkedCB=false,checkedRadio=false;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checkedCB=true;
}
else if(inputs[i].type == 'radio' && inputs[i].checked) {
checkedRadio=true;
}
if(checkedRadio && checkedCB) return true;
}
alert("You must select atleast one light bulb and a payment method.");
return false;
}
And you can put the attribute checked in any one radio button.
i.e.
<label><input type="radio" name="cc" value="Visa" checked>Visa</label><br>

If you would like to make sure at least one checkbox and one radio is checked before form submit then, you could introduce counters variable in your scripts that will count how many check box and radio button checked inside of the loop.
And before return just check at least one checkbox and one radio selected as follow:
if(checkbox_checked_count>=1&&radio_checked_count==1){
alert("Yahoo! You have successfully validated your form.")
return true;
}else{
alert("You must select a payment method.")
return false;
}
Your validateForm() function full script could like following one:
function validateForm(){
var inputs = document.getElementsByTagName('input');
var radio_checked_count=0;
var checkbox_checked_count=0;
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox"&&inputs[i].checked) {
checkbox_checked_count++;
}
if (inputs[i].type == "radio"&&inputs[i].checked) {
radio_checked_count++;
}
}
if(checkbox_checked_count>=1&&radio_checked_count==1){
alert("Yahoo! You have successfully validated your form.")
return true;
}else{
alert("You must select a payment method.")
return false;
}
}

Here is what your javascript is doing.
It checks the first radio button, finds that it is NOT checked so it executes the else statement and alerts that you must choose a card or whatever. Then it hits the return false statement and exits the loop (doesn't matter what it's returning, a return statement will exit the loop). That's all.
If you had checked the first checkbox using an attribute checked, it will find that the first radio button IS checked and then alert it and return out of the loop without checking the rest. Your for loop is not closed in the question if you want to edit it.

You should prompt user for payment selection only after for-loop, try this code snippet:
function validateForm() {
var payments = document.getElementsByName("cc");
var count = payments.length;
var selected = false;
while (count--)
if (selected = payments[count].checked)
break;
if (!selected) {
alert('Choose payment method');
return false;
}
return true;
}
<form name="bulbform" action="compute.php" onsubmit=" return validateForm()" method="post">
<p><strong>Payment Method</strong>
</p>
<label>
<input type="radio" name="cc" value="Visa">Visa</label>
<br>
<label>
<input type="radio" name="cc" value="Master Card">Master Card</label>
<br>
<label>
<input type="radio" name="cc" value="Discover">Discover</label>
<br>
<p>
<input type="submit" value="Order" />
<input type="reset" value="Clear form" />
</p>

Thanks to Mahesh Bansod for the help I used their example and tweaked it to my needs. Below is my working validation code for a textbox, checkbox and radio.
function validateForm(){
//check to make sure the name is not blank
var cusName = document.forms["bulbform"]["name"].value;
if (cusName == null || cusName == ""){
alert("Your name must be filled out.");
return false;
}
//check to see that atleast one radio and checkbox are checked
var inputs = document.getElementsByTagName('input');
var checkCheckBox=false, checkRadio=false; //set both rado and checkbox to false
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checkCheckBox=true; //set checkbox true if one is checked
}
else if(inputs[i].type == 'radio' && inputs[i].checked) {
checkRadio=true; //set radio true if one is checked
}
if(checkRadio && checkCheckBox) return true; //if both are true return true
}
//if checkbox is false alert user and return false
if(!checkCheckBox){
alert("You must select atleast one item.");
return false; //
}
//if radio is false alert user and return false
if(!checkRadio){
alert("You must select a payment method.");
return false;
}
}

Related

Validation with input[type="radio"] return always false

I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.
I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)
not exactly what i have, but...
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
and in JS i have...
var rdObj = document.getElementByName("radioGrp");
var selectedValue;
for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
alert("Select one option");
return false;
}else{
//do something with value of radio checked value
}
}
This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.
Any hel will be very appreciated
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.
You can attach a change event listener to each of your radios...
var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;
myRadios.forEach(radio => {
radio.addEventListener('change', changeHandler);
})
function changeHandler(evt) {
// do some check in here
console.log(evt.target.value)
}
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
...or you can attach a submit event handler to your form and do some checking of your data then.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);
function submitHandler(evt) {
evt.preventDefault();
const data = new FormData(evt.target);
const optionVal = data.get('radioGrp');
// do some check in here
if (!optionVal) {
console.log(`Please select a value`)
} else {
console.log(`Thanks for selecting ${optionVal}`)
}
}
<form>
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
<input type="submit">
</form>
You can try this:
function validateForm() {
var radios = document.getElementsByName("radioGrp");
var formValid = false;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
formValid = true;
break;
}
}
if (!formValid) {
alert("Select one option");
}
return formValid;
}
<form name="form1" action="#" onsubmit="return validateForm();" method="post">
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
<br>
<input type="submit" value="Submit">
</form>

How to pass values from a checkbox array to 3 inputs, without overwriting

I want to pass values of a checkbox array to 3 inputs, if I check in a value that sends to the first input, then the second checkbox to the second input and then the third checkbox to the third input, then if I choose another value of the checkbox that does not overwrite without first uncheck the checked checkbox value
It could be put an addeventlistener
<form action="#" method="post" class="demoForm" id="demoForm">
<fieldset>
<label><input type="checkbox" name="sports[]" value="cycling" /> cycling</label>
<label><input type="checkbox" name="sports[]" value="running" /> running</label>
<label><input type="checkbox" name="sports[]" value="visit gym" /> visit gym</label>
<label><input type="checkbox" name="sports[]" value="swimming" /> swimming</label>
<label><input type="checkbox" name="sports[]" value="team sports" /> team sport(s)</label>
<label><input type="checkbox" name="sports[]" value="other" /> other</label>
</fieldset>
</form>
<script type="text/javascript">
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
y=document.getElementById("chk1");
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
if ( this.checked) {
y.value=this.value;
} else {
y.value="";
}
}
</script>
<input type="text" name="chk1" id="chk1">
<input type="text" name="chk2" id="chk2">
<input type="text" name="chk3" id="chk3">
I hope to see the solution.
I created a set of conditional code which will work for you as i understood your question, and it's explained with comments along the way.
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
x = document.getElementById("chk1");
y = document.getElementById("chk2");
z = document.getElementById("chk3");
/*if a checkbox is checked and the first input is empty, then put the checkbox
value in the first input */
if ( this.checked && x.value =="") {
x.value = this.value;
/*now if the first input is filled already, check if the second is empty and put
the checkbox value into the second*/
} else if (this.checked && y.value =="") {
y.value = this.value ;
/*now if the second input is filled already, check if the third is empty and
put the checkbox value into the third*/
} else if (this.checked && z.value ==""){
z.value = this.value ;
/* if a checkbox is checked and all 3 inputs are filled already so it gets to
this condition, then alert the user and make the checkbox shouldn't be checked*/
}else if (this.checked) {
alert("First un-check another box to check this box");
this.checked = false;
/* if the user unchecked a checkbox, then check in which input the value of this
checkbox was displayed and empty this input */
} else if (!this.checked){
switch(this.value){
case y.value:
y.value="";
break;
case x.value:
x.value="";
break;
case z.value:
z.value="";
}
}
}

validation on checkbox not working

I am building a project on attendance management. In one of the forms of my project, I have multiple checkboxes. I want that at least one checkbox must be checked for form submission. I tried with Javascript but the problem is, it flag an alert even if one or more checkbox is checked.
Here is my js code :
function validat(){
var a = document.getElementsByTagName("checkbox");
var bool=false;
for(var i=0;i<a.length;i++){
if(a[i].checked==true){
bool=true;
}
}
if(bool){
return true;
}
else{
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
Here's my checkbox code :
echo "<input type='checkbox' name=duty[]' value='$row[university_roll_no]'></td></tr>";
Since you need at least one checkbox to be checked you don't have to loop through all the checkboxes in your form. In the first found checkkbox you can stop.
function validat(){
var checkboxes = document.getElementsByTagName("checkbox");
var atLeastOneCheckBoxIsChecked = false;
for( var i = 0; i < checkboxes.length; i++ ){
if( checkboxes[i].checked == true ){
atLeastOneCheckBoxIsChecked = true;
break;
}
}
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
A more functional way to do the same thing, is to be use Array.prototype.some method:
function validat(){
var atLeastOneCheckBoxIsChecked = document.getElementsByTagName("checkbox")
.some(checkbox => checkbox.checked == true);
if(atLeastOneCheckBoxIsChecked){
return true;
}
else {
alert("Sorry!Please select checkbox corresponding to students involved in duty leaves.");
return false;
}
}
Here you have an example:
function check() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
if (!checkedOne) {
console.log('please check at least one box!');
}
console.log(checkedOne);
}
<fieldset>
<legend>Choose some monster features</legend>
<div>
<input type="checkbox" id="scales" name="feature" onClick=check()
value="scales" checked />
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="horns" name="feature" onClick=check()
value="horns" />
<label for="horns">Horns</label>
</div>
<div>
<input type="checkbox" id="claws" name="feature" onClick=check()
value="claws" />
<label for="claws">Claws</label>
</div>
</fieldset>
You need to get input elements and check if type is "checkbox":
var a = document.getElementsByTagName("input");
for(var i = 0; i < a.length; i++) {
if(inputs[i].type == "checkbox") {
if (inputs[i].checked) {
bool=true;
}
}
}
Change your line
var a = document.getElementsByTagName("checkbox");
to
var a = document.querySelectorAll('input[type="checkbox"]');
I would have preferred you to use jQuery but with what you currently have, you need to do this:
var a = document.getElementsByTagName("input");
And then:
if(a[i].type == 'checkbox' && a[i].checked==true){
// Checked alert
}

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>

JSF Browse button - radio button check

I am using tomahawk library for browse button in my project.
Browse button code.
<td><t:inputFileUpload id="file" value="#{sampleService.file}"
valueChangeListener="#{sampleService.file}" /></td>
Radio Button Code
<td><input type="radio" /> This is compulsory</td>
I want to put a validation here,If the user has not checked the radio button,
it should display a message to check radio button.
thanks for any help
Give the radio button a fixed id and check its checked state in the onclick of the file field and if it's false, then display a message (alert?) and return false to block the browse button.
E.g.
<t:inputFileUpload id="file" value="#{sampleService.file}" valueChangeListener="#{sampleService.file}"
onclick="if (!document.getElementById('compulsory').checked) { alert('Please check radio button'); return false; }"
/>
<input type="radio" id="compulsory" /> This is compulsory
You could also wrap it in a JS function:
function checkCompulsory() {
if (!document.getElementById('compulsory').checked) {
alert('Please check radio button');
return false;
} else {
return true;
}
}
with
<t:inputFileUpload id="file" value="#{sampleService.file}" valueChangeListener="#{sampleService.file}"
onclick="return checkCompulsory()"
/>
<input type="radio" id="compulsory" /> This is compulsory
If you search here you will find it but for your intrest
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio'){
if(radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
} else {
alert('This is compulsory')
}
}
}

Categories