validation on checkbox not working - javascript

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
}

Related

Checkbox State Persistence before and after form submission

I am new to web developing. Apologies, if this is too simple but could not find the right way to fix this issue.
I have been asked to make a simple form with several checkboxes having a unique name and different values.
No problem for that. The issue I am encountering is that I have also been asked that I need to have all the checkboxes checked by default before submission and only to keep the checkboxes that remain checked, checked after the form submission. My code below does not make them all checked by default but save the results after form submission. Even adding the statement checked on the input tag does not change much.
<form onsubmit="return saveCheckboxValue();">
<label for="checkbox1">Option 1</label>
<input type="checkbox" id="checkbox1">
<br>
<label for="checkbox2">Option 2</label>
<input type="checkbox" id="checkbox2">
<br>
<label for="checkbox3">Option 3</label>
<input type="checkbox" id="checkbox3">
<br>
<input type="submit" value="Submit">
</form>
<script>
function saveCheckboxValue() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
localStorage.setItem(checkboxes[i].id, true);
} else {
localStorage.removeItem(checkboxes[i].id);
}
}
return true;
}
window.onload = function() {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || false;
}
};
</script>
I tried to change the value to true
> window.onload = function() { // Get all checkbox elements var
> checkboxes = document.querySelectorAll("input[type='checkbox']");
>
> for (var i = 0; i < checkboxes.length; i++) {
> checkboxes[i].checked = JSON.parse(localStorage.getItem(checkboxes[i].id)) || true; } };
But by doing this, the checkboxes will be checked by default which is good, but if I uncheck some and submit the form, even the unchecked ones will be checked after the form submission.
From what I understood you want the boxes to be checked by default only at the first load, then the values to be persistent.
Would that work for you ?
in the saveCheckboxValue function, change the else condition to set the item to false instead of deleting it.
window.onload = function () {
// Get all checkbox elements
var checkboxes = document.querySelectorAll("input[type='checkbox']");
var val;
for (var i = 0; i < checkboxes.length; i++) {
val = JSON.parse(localStorage.getItem(checkboxes[i].id))
if (val == null) {
checkboxes[i].checked = true;
} else{
checkboxes[i].checked = val;
}
}
};

Javascript form validation checkbox and radio not working

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;
}
}

check if selected option and checkbox is checked

I have some problems here with javascript.
I want someone to choose an option and a checked box, and if both are checked then other checkboxes should not be able to click.
I had tried to give the function 2 parameters (one is for the option and one for the checkbox).
function bs(id /*,chbxvalue */ )
{
var selectElement = document.getElementById(id);
var selectValue = selectElement.options[selectElement.selectedIndex].value;
//var select2Element = document.getElementById(chbxvalue);
//var selectCHBXval = select2Element.options[select2Element.selectedIndex].value;
if((selectValue == "banana" ) /*&& (document.getElementById("apple").checked == true )*/ )
{
document.getElementById("juice").checked = true;
}
else if(selectValue == "Salad")
{}
}
The thing in the comments doesn't work.
<div id="flavor"><br />
<select id="bss" name="beh" onChange="bs('bss')">
<option value="banana" >banana</option>
<option value="pinapple" >pinapple</option>
</select>
</div>
<div id="divcontainer" class="cont" style="display:block;">
<input type="checkbox" name="app" id="apple" value="appl" />Apples <br />
<input type="checkbox" name="juices" id="juice" value="fj" />Fruitjuice <br />
</div>
I've changed the names here. Has anybody an idea? Sorry, I am not so good with javascript... .
Sounds like you'd like to use simply
document.getElementById("...").disabled=true;
Or if you'd like to disable more checkboxes at once, assign them a class, and use
elements = document.getElementsByClassName("my_class");
for(var i = 0; i < elements.length; ++i)
{elements[i].disabled = "true"; }
I'm not exactly sure if this is what you're after, but it seems like you want some kind of conditional logic. I made a fiddle to illustrate it: https://jsfiddle.net/75uLereo/
var radios = document.myform.type,
select = document.myform.flavor;
for(var i = 0; i < radios.length; i++){
radios[i].addEventListener('change', checkValues);
}
select.addEventListener('change', checkValues);
function checkValues(){
var select = document.myform.flavor,
selectedValue = select.options[select.selectedIndex].value,
radioValue = document.querySelector('input[name = "type"]:checked').value;
if(radioValue !== "undefined"){
switch(selectedValue){
case 'none':
case 'banana':
case 'strawberry':
alert("This is "+selectedValue+" and "+radioValue+". Do some conditional logic with the values!");
break;
default:
break;
}
}
}
This binds a function to change events on the radio buttons and the select and then uses a switch on the different values to do whatever you want it to do.
Updated:
I made another example, with checkboxes and the bool value from the checkboxes if they are selected
https://jsfiddle.net/75uLereo/2/

display alert on each selected check box from a group of checkboxes

I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();

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>

Categories