multiple checkboxes at least 1 required in html 5 - javascript

I want as HTML error message rather than an alert message, I've found few solutions but none are not working as hoped
$('form').on('click', '.required_group', function() {
$('input.required_group').prop('required', $('input.required_group:checked').length === 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="whatever" value="1" required class="required_group" />
<input type="checkbox" name="whatever" value="2" required class="required_group" />
<input type="checkbox" name="whatever" value="3" required class="required_group" />
<input type="checkbox" name="whatever" value="4" required class="required_group" />
<input type="submit" name="submit" />
</form>

$('form').on('click', '.required_group', function() {
var flag=false;
$('.required_group').each(function(e){
if (this.checked) {
flag=true;
}
});
if(!flag){
// Do your code for Error Message
}
});

Here is a method with a custom error message.
It looks at everything with the class required_group and counts every instance where it is checked. If the number is 0 it sets a custom message and triggers it, however, if there is one or more it will reset the message and trigger a submit.
function validateGrp() {
let things = document.querySelectorAll('.required_group')
let checked = 0;
for (let thing of things) {
thing.checked && checked++
}
if (checked) {
things[things.length - 1].setCustomValidity("");
document.getElementById('checkGroup').submit();
} else {
things[things.length - 1].setCustomValidity("You must check at least one checkbox");
things[things.length - 1].reportValidity();
}
}
document.querySelector('[name=submit]').addEventListener('click', () => {
validateGrp()
});
<form id="checkGroup">
<input type="checkbox" name="whatever" value="1" class="required_group" />
<input type="checkbox" name="whatever" value="2" class="required_group" />
<input type="checkbox" name="whatever" value="3" class="required_group" />
<input type="checkbox" name="whatever" value="4" class="required_group" />
<button name="submit">Submit</button>
</form>

Related

radio buttons won't check / uncheck

I have some radio buttons in my web page.
when clicking the radio button it checks but when i click again it doesn't un-check.
i tried to add a JS function onclick
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.checked == true){
this.checked = false;
}
else {
this.checked = true;
}
}))
when I added this method it allowed my to uncheck but didn't allow me to check any of them!
what can I be missing?
these are my checkboxes:
<input type="radio" id="name" name="name"><br>
<input type="radio" id="age" name="age"><br>
<input type="radio" id="email" name="email"><br>
They all have different name attribute values - therefore they can only be checked (because they're not comparing to another sibling radio value). I think you might be looking for type="checkbox" instead:
<input type="checkbox" id="name" name="name"><br>
<input type="checkbox" id="age" name="age"><br>
<input type="checkbox" id="email" name="email"><br>
Example: Hold down Ctrl (⌘ on mac) key to uncheck.
var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
radios[i].onclick = function(e) {
if(e.ctrlKey || e.metaKey) {
this.checked = false;
}
}
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />
Use <input type="checkbox", not <input type="radio".
Radio button is used where you have to select one of some options (which must have same name).
For example,
<input type="radio" name="gender" id="male" value="male"> <br>
<input type="radio" name="gender" id="female" value="female"> <br>
<input type="radio" name="gender" id="other" value="other">
Know more about radio button and check boxes.
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.value == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 1;
}
else {
this.checked = false;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 0;
}
}))
<input type="radio" value="0" id="name" name="test"><br>
<input type="radio" value="0" id="age" name="test"><br>
<input type="radio" value="0" id="email" name="test"><br>
This code allows the user to deselect a radio button:
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(! this.value0 || this.value0 == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 1;
} else {
this.checked = false;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 0;
}
}))
It improves the answer of Sato Takeru.

Jquery get all checked checkboxes values

I want to select all value checked. My checkbox name are type[]
When I remove the [] it is working . Please see my code below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script>
<input type="checkbox" name="type[]" value="GFG" id="feaut" /> GFG:
<input type="checkbox" name="type[]" value="Geeks" id="feaut" /> Geeks:
<input type="checkbox" name="type[]" value="Geek" id="feaut"/> Geek:
<input type="checkbox" name="type[]" value="portal" id="feaut" /> portal:
<br>
<button>
click here
</button>
<script>
$('button').on('click', function() {
var array = [];
$("input:checkbox[name=type]:checked").each(function() {
array.push($(this).val());
});
console.log(array.toString());
});
</script>
Use [type=checkbox] to select inputs of type checkbox. Also, since [] are illegal characters in unquoted selector values, surround them in quotes: [name='type[]']
$('button').on('click', function() {
var array = [];
$("input[type=checkbox][name='type[]']:checked").each(function() {
array.push($(this).val());
});
console.log(array.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<input type="checkbox" name="type[]" value="GFG" id="feaut" /> GFG:
<input type="checkbox" name="type[]" value="Geeks" id="feaut" /> Geeks:
<input type="checkbox" name="type[]" value="Geek" id="feaut" /> Geek:
<input type="checkbox" name="type[]" value="portal" id="feaut" /> portal:
<br>
<button>
click here
</button>

Javascript radio group by button

How to display an alert msg when all radio button checked to no? I only know check radio by individual only.
//I only know this method
$('#attraction1').change( function(){
if ($(this).is(':checked')) {
alert('Yes');
}
});
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br>
Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" name="individual" value="n" /> No
<br>
Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
In this case you should check something like this
$('#some_button').click( function(){
if ($('input[type="radio"][value="n"]:checked').length == 3) {
alert('Yes');
}
});
You can use a common class for all radio button with no value and a javascript array every method.
This line const radioNames = [...document.getElementsByClassName('no')]; will get all the radio button with no value ... is spread operator and will convert collection so that array method can be used on that collection.
This line item.addEventListener('change', checkIfAllNo) will attach event change to radio button with value no so that it checks the value for all other radio button
Array method every will return true if all the value in that array satisfies the condition.
So in this line radioNames.every(item => {return item.checked;}); if all the radio button with no value is checked then isAllFalse will be true & the alert will be triggered.
const radioNames = [...document.getElementsByClassName('no')];
function checkIfAllNo() {
const isAllFalse = radioNames.every(item => {
return item.checked;
});
if (isAllFalse) {
alert('All False')
}
}
radioNames.forEach((item) => {
item.addEventListener('change', checkIfAllNo)
})
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" class="no" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" class="no" name="individual" value="n" /> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" class="no" name="planBoard" value="n" /> No
In case you have an indeterminate number of inputs you can collect the values for every group and then check if all values match
$("input[type='radio']").change(function() {
// Extract all the radio group names
names = $.unique($('input[type="radio"]').map((v, e) => $(e).attr('name')))
// Collect the value for each group.
// Account for groups that are not selected yet
vals = $.map(names, function(name) {
return $(`input:radio[name="${name}"]:checked`).val() || 'undefined';
})
// Check if collected values match 'n'
console.log(vals.every(v => v == 'n'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" /> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" /> Yes
<input type="radio" id="individual2" name="individual" value="n" checked/> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
#ForeverTwoWheels
Please try this code,To Javascript radio group by button
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Radio Buttons</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="yes"> Yes
<input type="radio" name="choice" value="no"> No
<input type="button" id="btn" value="Show Selected Value">
</form>
<script>
const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
alert(selectedValue);
};
</script>
</body>
</html>
I hope this information will be usefull for you.
Thank you.

How to check for a checkbox to be checked?

I have 2 checkboxes. I need one, not both, but at least 1 to be checked. It is not a multiple selection but zero is not accepted. If one is checked, this line will work jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click'); otherwise it should alert. The following makes it alerting all the time.
UPDATE
I am not using the submit button or I would have used the validate plugin. It is a normal button to go next in the wizard <button type="button" class="btnNext">Next step</button>
HTML
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
</div>
JS
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
var isChecked = false;
$('input[type=checkbox]').on("change", function () {
isChecked = true;
});
if ( isChecked ) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});
With jQuery you can use is:
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('input[name="hi"]').is(':checked')) {
console.log('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="checkbox" name="hi" value="hi">Hallo<br>
<input type="checkbox" name="gb" value="gb">Tschuss<br>
<input type="submit" value="Submit">
</form>
Adapted to your code:
$('.btnNext').click(function(e) {
e.preventDefault();
if ($('#usp-category-7').is(':checked') || $('#usp-category-8').is(':checked')) {
console.log('at least one is checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
<button class="btnNext">Next</button>
</div>
Thanks to a comment, I personally resolved it like this, making them radio buttons. But I will accept the other answer as it is correct.
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
if($('input[type=radio').is(':checked')) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});

disable select form if radio is checked

How can I disable a select form dropdown if a radio button is selected?
I would like the #preference form to be disabled if the user selects the #no radio button and it to be enabled again if the user selects #yes or #maybe.
This is my form code -
<form name="xmas" id="xmas" action="send_mail.php" method="post">
<input type="radio" name="choice" value="Yes" id="yes"/><label for="yes">Yes - I would like to take up the offer</label>
<input type="radio" name="choice" value="No" id="no"/><label for="no">No - I'm not ready to order yet</label>
<input type="radio" name="choice" value="Maybe" id="maybe"/><label for="maybe">Maybe - I'm not sure, would you please give me a call</label><br />
<div class="secondlineform">
<input type="text" name="name" class="textfield" value="Name" onfocus="if(this.value=this.defaultValue){this.value=''}; return false;"/>
<input type="text" name="email" class="textfield" value="Email" onfocus="if(this.value=this.defaultValue){this.value=''}; return false;"/>
<input type="text" name="company" class="textfield" value="Company" onfocus="if(this.value=this.defaultValue){this.value=''}; return false;"/>
<select class="dropselect" name="preference" label="Preference" id="preference">
<option selected="selected" disabled="disabled" value="Preference">Preference</option>
<option value="Alcohol Package">Alcohol Package</option>
<option value="Gift Card Package">Gift Card Package</option>
</select>
<input type="submit" value="" name="submit" id="submit" class="submit"/>
</div>
</form>
And this is my script code -
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
​
var update_select = function () {
if ($('#no').is(':checked')) {
$('#preference').attr('disabled', "disabled");
}
else {
$("#preference").removeAttr("disabled");
}
};
$(update_select);
$('#no').change(update_select);
</script>
Thanks very much for any answers! I've been researching this for ages and all the solutions I find don't seem to solve my issue.
you are adding change event for only No radio, change it to :
$("input[name='choice']").change(update_select);
Demo:: jsFiddle
$('input[type=radio]').change(update_select);​
You need to apply the update_select function to the rest of the radio button,like this
var update_select = function () {
$('#preference').attr('disabled', $('#no').is(':checked'));
};
$('#no').change(update_select);
$('#yes').change(update_select);
$('#maybe').change(update_select);
Here is the fiddle: http://jsfiddle.net/QXkhM/
Wrap your radio button list by an ul and give it an ID.
For example:
<ul id="offer">
<input type="radio" name="choice" value="Yes" id="yes"/><label for="yes">Yes - I would like to take up the offer</label>
<input type="radio" name="choice" value="No" id="no"/><label for="no">No - I'm not ready to order yet</label>
<input type="radio" name="choice" value="Maybe" id="maybe"/><label for="maybe">Maybe - I'm not sure, would you please give me a cal
l</label><br />
</ul>
var update_select = function () {
if ($('#no').is(':checked')) {
$('#preference').attr('disabled', "disabled");
}
else {
$("#preference").removeAttr("disabled");
}
};
$(update_select);
$('#offer').change(update_select);
And it will work

Categories