Make only 2 checkboxes checked per form - javascript

I have multiple forms in one page with the same input names. The only difference between forms is the forms that contain them.
For the groups of checkboxes on my form, I only want to allow two checkboxes out of three to be checked but I don't want the checkboxes in one form to affect another.
I have a jsFiddle of what I have now.
I have it setup now that only two checkboxes can be checked out of three but that's for the entire document, not form specific.
The forms in my page are created with a loop and the id of the form is the only difference between them.
Anyone able to help with this?
https://jsfiddle.net/likwidmonster/3zbs61q5/
$('input[type=checkbox][name=group]').on('change', function(e) {
if ($('input[type=checkbox][name=group]:checked').length < 2) {
$('input[type=checkbox][name=group]:not(:checked)').prop('disabled', false);
}
if ($('input[type=checkbox][name=group]:checked').length == 2) {
$('input[type=checkbox][name=group]:not(:checked)').prop('disabled', 'disabled');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>
Form 1
</h4>
<form id="form_1">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>
<div>
<h4>
Form 2
</h4>
<form id="form_2">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>

Since your forms are dynamic maybe this will be of better use.
I did create a jsfiddle and post it in the comment but that's only good for those two forms. Maybe you want to add more? JSFiddle Demo
this.parentNode.id;
this is used to target the element triggering the function, .parentNode is used to get the form element and .id is used to get the ID of the form so you can target that specific form meaning you only need one if condition to run this for all the forms!
$('form input[type=checkbox][name=group]').on('change', function(e) {
var MyForm=this.parentNode.id;
if ($('form[id='+MyForm+'] input[type=checkbox][name=group]:checked').length == 2) {
$('form[id='+MyForm+'] input[type=checkbox][name=group]:not(:checked)').prop('disabled', 'disabled');
}else{
$('form[id='+MyForm+'] input[type=checkbox][name=group]:not(:checked)').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>
Form 1
</h4>
<form id="form_1">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>
<div>
<h4>
Form 2
</h4>
<form id="form_2">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Here's a working solution. Hope it helps!
$('input[type=checkbox][name=group]').on('change', function(e) {
if ($('#form_1 input[type=checkbox][name=group]:checked').length === 2) {
$('#form_1 input[type=checkbox][name=group]:not(:checked)').prop('disabled', 'disabled');
}else{
$('#form_1 input[type=checkbox][name=group]:not(:checked)').prop('disabled', false);
}
if ($('#form_2 input[type=checkbox][name=group]:checked').length === 2) {
$('#form_2 input[type=checkbox][name=group]:not(:checked)').prop('disabled', 'disabled');
}else{
$('#form_2 input[type=checkbox][name=group]:not(:checked)').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
<h4>
Form 1
</h4>
<form id="form_1">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>
<div>
<h4>
Form 2
</h4>
<form id="form_2">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>

Use a function to initialize your event handler for each group. Also use a different group name.
https://jsfiddle.net/3zbs61q5/3/
function setupCheckboxGroup(grpName){
$('input[type=checkbox][name='+grpName+']').on('change', function(e) {
if ($('input[type=checkbox][name='+grpName+']:checked').length < 2) {
$('input[type=checkbox][name='+grpName+']:not(:checked)').prop('disabled', false);
}
if ($('input[type=checkbox][name='+grpName+']:checked').length == 2) {
$('input[type=checkbox][name='+grpName+']:not(:checked)').prop('disabled', 'disabled');
}
});
}
setupCheckboxGroup('group');
setupCheckboxGroup('group2');
<div>
<h4>
Form 1
</h4>
<form id="form_1">
<input type="checkbox" name="group" value="1">
<input type="checkbox" name="group" value="2">
<input type="checkbox" name="group" value="3">
</form>
</div>
<div>
<h4>
Form 2
</h4>
<form id="form_2">
<input type="checkbox" name="group2" value="1">
<input type="checkbox" name="group2" value="2">
<input type="checkbox" name="group2" value="3">
</form>
</div>

Related

Set hidden value based on radio button selection

Cannot find an answer:
I have searched Stack Overflow, however, despite finding lots of similar posts — and more complicated situations — I still couldn't find an answer to the issue I am trying to solve.
Here's my issue:
I have four radio buttons, and one hidden field:
<!-- My HTML Document -->
<form action="/my-doc.html" method="post">
<!-- The 4 Radio Buttons-->
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<!-- The Hidden Field -->
<input type="hidden" name="criteria" value="1">
<!-- My Submit Button -->
<input type="submit" name="action" value="Go">
</form>
What I need to do is set the value of <input type="hidden" name="criteria" value="1"> so that it is 0
Like this: <input type="hidden" name="criteria" value="0">
...but only after the user selects either the first, or second, radio button. The value of the hidden field should remain as being equal to 1 if any other radio button is selected.
How does a person do this using JavaScript?
Requirements: "Looking for a VanillaJS answer."
you can try below option
In javascript
function setValue() {
var selectedRadio = '';
var games = document.getElementsByName('game')
for (var i = 0; i < games.length; i++) {
if (games[i].checked) {
selectedRadio = games[i].value;
}
}
document.getElementById("hdnSelectedRadValue").value = (selectedRadio == "1" || selectedRadio == "2") ? "0" : "1";
return false;
}
Changes to do in HTML side
<body style="background-color: #f2f2f2;">
<form action="some.htm" method="post">
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="text" name="criteria" id="hdnSelectedRadValue">
<input type="submit" name="action" value="Go" onclick="setValue();">
</form>
</body>
var radios =
document.querySelectorAll('input[type=radio][name="game"]');
radios.forEach(radio => radio.addEventListener(
'change', () => {
document.getElementsByName("criteria")[0].value =
parseInt(radio.value, 10) > 2 ? '1' : '0';
}
));
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" value="1">
<input type="submit" name="action" value="Go">
You can simply listen to "change" events on all of the radio buttons, then just set the value accordingly.
Here's the snippet code I have written and tested
(function(){
let hdfValue = document.getElementById("myhiddenfield")
let radioButtons = document.querySelectorAll('input[name="game"]');
let submitButton = document.querySelector('input[name="action"]')
radioButtons.forEach((input) => {
input.addEventListener('change', function(e){
let radioButtonValue = e.target.value
if(radioButtonValue == 1 || radioButtonValue == 2){
hdfValue.value = 0;
} else {
hdfValue.value = 1;
}
});
});
submitButton.addEventListener("click", function() {
console.log(hdfValue.value)
});
})()
<form>
<input type="radio" name="game" value="1" checked> First
<input type="radio" name="game" value="2"> Second
<input type="radio" name="game" value="3"> Third
<input type="radio" name="game" value="4"> Fourth
<input type="hidden" name="criteria" id="myhiddenfield" value="1">
<input type="button" name="action" value="Go">
</form>

jQuery Selectors or 'if' trouble

This code should prohibit clicking more than two radiobuttons in total (there are three groups of such buttons).
This works when there is no container 'label', but when it is, it doesn't work (it looks like that 'if' construct is not working; everything that is written outside of it works fine)
how to make it work without removing the label? Is there any solutions?
var radio_limit = 2;
$('.pricing-levels-3 label input').on('change', function(evt) {
if($(this).siblings(':checked').length >= radio_limit) {
this.checked = false;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricing-levels-3">
<p><strong>Select 2 Levels</strong></p>
<label>
<input type="radio" name="vehicle" value="1">Level 1<br>
<input type="radio" name="vehicle" value="2">Level 2<br>
<input type="radio" name="vehicle" value="3">Level 3<br>
</label>
<label>
<br>
<input type="radio" name="vehicle2" value="1">Level 1<br>
<input type="radio" name="vehicle2" value="2">Level 2<br>
<input type="radio" name="vehicle2" value="3">Level 3<br>
</label>
<label>
<br>
<input type="radio" name="vehicle3" value="1">Level 1<br>
<input type="radio" name="vehicle3" value="2">Level 2<br>
<input type="radio" name="vehicle3" value="3">Level 3<br>
<br>
</label>
</div>
You are looking for siblings, which they were without labels. Now with labels they are not sibling they are cousins. To fix we read all radio buttons in same div using closest(). Also use prop to check a radio button. Do this:
var radio_limit = 2;
$('.pricing-levels-3 label input').on('change', function(evt) {
if($(this).closest('div').find('input:checked').length >= radio_limit) {
$(this).prop('checked', false);
};
});

jQuery multi-row form: disable submit until each row has a radio checked

I have a multi-row form with single choice radio buttons in each row. I'd like the final <button> tag to be disabled until a radio button as been checked from each row.
I currently have a solution from a previous question (jQuery multi-step form: disable 'next' button until input is filled in each section) that removes the disabled attribute from the button when you select any radio button but i'd like to be more specific if possible.
Is this possible? Here's a Codepen of what I'm working on currently: https://codepen.io/abbasarezoo/pen/vdoMGX - as you can see when hit any radio in any row the disabled attribute comes off.
HTML:
<form>
<fieldset>
<div class="radio-group">
<h2>Select one answer per row</h2>
<h3>Row 1</h3>
<label for="radio-1">Radio 1</label>
<input type="radio" id="radio-2" name="radio-row-1" />
<label for="radio-2">Radio 2</label>
<input type="radio" id="radio-2" name="radio-row-2" />
<label for="radio-3">Radio 3</label>
<input type="radio" id="radio-3" name="radio-row-3" />
</div>
<div class="radio-group">
<h3>Row 2</h3>
<label for="radio-4">Radio 1</label>
<input type="radio" id="radio-4" name="radio-row-4" />
<label for="radio-5">Radio 2</label>
<input type="radio" id="radio-5" name="radio-row-5" />
<label for="radio-6">Radio 3</label>
<input type="radio" id="radio-6" name="radio-row-6" />
</div>
<button disabled>Next</button>
</fieldset>
</form>
jQuery:
$('fieldset input').click(function () {
if ($('input:checked').length >= 1) {
$(this).closest('fieldset').find('button').prop("disabled", false);
}
else {
$('button').prop("disabled", true);
}
});
You need to specify the same name for the radio button group so that only one radio button is selected per row. Then, you can simply compare the length of the checked radio button with the length of the radio button group like this,
$('fieldset input').click(function () {
var radioLength = $('.radio-group').length;
if ($('input:checked').length == radioLength) {
$('fieldset button').prop("disabled", false);
}
else {
$('button').prop("disabled", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<div class="radio-group">
<h2>Select one answer per row</h2>
<h3>Row 1</h3>
<label for="radio-1">Radio 1</label>
<input type="radio" id="radio-2" name="radio-row-1" />
<label for="radio-2">Radio 2</label>
<input type="radio" id="radio-2" name="radio-row-1" />
<label for="radio-3">Radio 3</label>
<input type="radio" id="radio-3" name="radio-row-1" />
</div>
<div class="radio-group">
<h3>Row 2</h3>
<label for="radio-4">Radio 1</label>
<input type="radio" id="radio-4" name="radio-row-2" />
<label for="radio-5">Radio 2</label>
<input type="radio" id="radio-5" name="radio-row-2" />
<label for="radio-6">Radio 3</label>
<input type="radio" id="radio-6" name="radio-row-2" />
</div>
<button disabled>Next</button>
</fieldset>
</form>

How do I grab the selected radiobox value from a particular form?

I have some generated HTML along the lines of this.
<form id="form_56">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
The form id can be anything, but I want to take a form ID and return the selected value from 0 to 6.
I tried following the questions here, but they didn't seem to translate easily to a specific form.
$('#form_56:radio[name=option]:checked').val();
I'm able to use the selector to grab the proper form, but everything I've attempted to get the selected value has returned undefined.
Thanks for your time.
First, you need to change the colon to a space or " > ".
Second you need to change radio to input.
$('#form_56 input[name=option]:checked').val();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_56">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
<a href="javascript:console.log($('#form_56 input[name=option]:checked').val());">
<button>Test</button>
</a>
$("#form_56 input:radio[name='option']").val()
You need an event for listening when it changes
see example
$(function() {
$("#form_56 input:radio[name='option']").click(function() {
var val = $(this).val();
alert(val);
});
});
https://jsfiddle.net/rodrigo/cp8rd7h0/
problem in your code: on change event not assign to radio button so undefined alert popup
here is solution:
$(document).ready(function () {
$('input[type=radio]').on('change', function () {
alert($('input[name=option]:checked', '#form_56').val());
});
});
For any form:
$('form>input[type="radio"]:checked').val()
With id:
$('#form_56>input[type="radio"]:checked').val()
It will return selected value or undefined, if no value selected.
Good luck!
function getSelectedValue()
{
return $('form>input[type="radio"]:checked').val();
}
$(function() {
$('button').on(
'click',
function() {
console.log(getSelectedValue() + ' selected');
}
);
});
form {display: inline}
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<form id="randomId-839054763">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>
<button>Log value</button>

Check-boxes with Radio-buttons quality

I need check-boxes list that has one quality of radio-buttons:
That you can check only one of them.
I don't want to use radio-buttons, becouse I need other qualities of check-boxes, like that you can un-check it by additional click.
Is there any simple way to do it?
I can use javascript, including knockout and jquery libraries.
DEMO
$(function() {
$(':checkbox').on('change',function() {
$(':checkbox[name=' + this.name + ']:checked').not(this).prop('checked',false);
});
});
HTML:
<fieldset>
<legend>Group1</legend>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
</fieldset>
<fieldset>
<legend>Group2</legend>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
</fieldset>
Checkbox Group exactly like a radio button group
jsfiddle:
Checkbox Group
Javascript:
$("input:checkbox").click(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).attr("checked",false);
$(this).attr("checked",true);
});
Checkbox Group you can remove all checked.
jsfiddle:
Checkbox Group(can remove all checked)
Javascript:
$("input:checkbox").change(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).not(this).prop("checked",false);
$(this).prop("checked",!this.checked);
});

Categories

Resources