How to detect which checkboxes are checked? - javascript

I need to use checkboxes, but there's no submit button-- it needs to have an effect on the page the user is already on, the same page that contains the checkboxes.
Essentially, I have ~10 checkbox elements. The user selects a certain number of them, then clicks a button element. When they click that element, I need to detect which checkboxes have been checked. What's the best way to do that with the shortest amount of code?

Have all your checkboxes share the same class.
var allChecked = $(".checkBoxClass:checked");
This will return a list of checked checkboxes in the class checkBoxClass. Now you can iterate each element and operate on them.
for(var i=0; i<allChecked.length; i++) {
console.log("Checkbox " + $(allChecked[i]).val().toString() + " is checked");
}

Any of these should work:
$('input:checked');
$('input:checkbox:checked');
$('input:checkbox').filter(':checked');

Try:
<input type="checkbox" id="1" value="one"/>
<input type="checkbox" id="2" value="two"/>
<input type="checkbox" id="3" value="three"/>
<input type="button" onclick="validate()" value="Check"/>
<script type="text/javascript">
function validate(){
var chkArr = document.querySelectorAll('input[type="checkbox"]');
var notChecked='';
for(var i=0;i<chkArr.length;i++){
if(!chkArr[i].checked)
notChecked += chkArr[i].value
}
if(notChecked.length)
alert(notChecked);
}
</script>

Related

Display value from only checked checkbox and if other checkboxes are checked uncheck them

Lets say that I have 3 checkboxes:
<input type="checkbox" value="25,99" name="price">
<input type="checkbox" value="15,99" name="price">
<input type="checkbox" value="10,99" name="price">
and I want to display the value of the checked checkbox in a div, but only one checkbox can be active at a time.
I was trying to marry these two examples together but this seams kinda messy and overkill:
only one checked at the time
http://jsfiddle.net/MQM8k/
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
with this link to live
$(document).ready(function() {
$("button").click(function(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
});
alert("My favourite sports are: " + favorite.join(", "));
});
});
Thanks
An easy way is to uncheck all the checkboxes as the first thing you do upon detecting a click, and then re-check the one you are on.
$('.prx').click(function(){
$('.prx').prop('checked', false);
$(this).prop('checked', true);
let prx = $(this).val();
$('#msg').text(prx);
});
#msg{margin-top:20px;padding: 10px; background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
25.99 <input type="checkbox" class="prx" value="25,99" name="price"><br>
15.99 <input type="checkbox" class="prx" value="15,99" name="price"><br>
10.99 <input type="checkbox" class="prx" value="10,99" name="price"><br>
<div id="msg"></div>
$(document).on("click", ".prx", function (){
var self = $(this);
$('.prx').not(self).prop('checked', false);
self.prop('checked', true);
alert(self.val());
});
You should really consider making this input a radio button.
You're essentially breaking the UX of checkboxes to not allow multiple selections. Radio button inputs do this behavior (one selection at a time) by default, will have expected tab actions for accessibility users and won't need all this extra JS.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)
ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204
I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?
$jqLib("#ModellingTagID_*").change(function(){
var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
$jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
});
you can apply same class to all those checkboxes
<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
<li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>
and then you can make function for it's change event like this.
$(function(){
$('.yourcbclass').on('change', function() {
if($(this).is(':checked'))
{
//do your stuff here
}
});
});
see if this helps..
Very simple using this way:--
$("#envoyer").click(function(e) {
var myArray = [];
$(":checkbox:checked").each(function() {
myArray.push(this.value);
});
if(myArray == ''){
alert('Please check');
}else{
alert("Checked: " + myArray.join(","));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
one<input type="checkbox" name='checkbox0' value="one_name" checked>
two<input type="checkbox" name='checkbox1' value="one_name1">
three<input type="checkbox" name='checkbox2' value="one_name2">
<input type="button" id="envoyer" value="Envoyer Reponse" />
</body>
</html>
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.
cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.
$(document).ready(function(){
$('.someclass').on('change', function() {
alert($(this).attr("id"));
});
});

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

selection multiple radio button by java script using button id

all the radio button names are to be same. so i want to call using their using id. is it valid to call them by id? if it is please help me about it.
function selectAll( prefix, set ) {
var form = document.forms[0], //Get the appropriate form
i = 0,
radio;
while( radio = form[prefix + ++i] ) //Loop through all named radio# elements
for( var j = 0; j < radio.length; j++ ) //Loop through each set of named radio buttons
if( radio[j].value == (set ? "yes" : "no") ) //Selector based on value of set
radio[j].checked = true; //Check that radio button!
while($row=mysqli_fetch_assoc($result))
{
echo"<tr><td>{$row['roll']}</td>
</td><td></td><td></td><td></td><td>
<td><input id='file' type='radio' name='radio[$i]' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='radio[$i]' value='No'>NO</td></tr>";
$i++;
}
Try something like this: give each "Yes" radio button unique id, loop through them and set checked property to true:
`function selectAll()
{
for(i = 1; i < 10; i++)
{
var id = "file" + i;
var element = document.getElementById(id);
element.checked = true;
}
}`
And your php code:
`echo "<tr><td>$row</td>
</td><td></td><td></td><td></td><td>
<td><input type='radio' name='radio$i' id='file$i' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='radio$i' value='No'>NO</td>`</tr>";`
Of course as others suggested the best/quicekst is to use jquery.
If your Main focus is to select all the radio button you can give a class name for the radio button and make it get checked on button click event.
we will sugesst to use jquery instead of javascript.
You just have to include one jquery library and can jquery code at any place of your javascript code.
As jquery is advanced form of javascript and is easy to use. so all the task will better perform in jquery by selecting simply radio button class and than checked them.
<div id="radioList">
<input type="radio" class="check" />
<input type="radio" class="check" />
<input type="radio" class="check" />
<input type="radio" class="check" />
<input type="radio" class="check" />
</div>
below jquery wll help
$('.check').prop("checked", true)
or
$('#radioList input:radio').prop("checked", true)

How to clear radio button in Javascript?

I have a radio button named "Choose" with the options yes and no. If I select any one of the options and click the button labeled "clear", I need to clear the selected option, using javascript. How can I accomplish that?
You don't need to have unique id for the elements, you can access them by their name attribute:
If you're using name="Choose", then:
With recent jQuery
$('input[name=Choose]').prop('checked',false);
With old jQuery (<1.6)
$('input[name=Choose]').attr('checked',false);
or in pure JavaScript
var ele = document.getElementsByName("Choose");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
Demo for JavaScript
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)
document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;
An example of how the radio buttons should be named:
<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
Simple, no jQuery required:
clear
<script type="text/javascript">
function clearChecks(radioName) {
var radio = document.form1[radioName]
for(x=0;x<radio.length;x++) {
document.form1[radioName][x].checked = false
}
}
</script>
YES<input type="radio" name="group1" id="sal" value="YES" >
NO<input type="radio" name="group1" id="sal1" value="NO" >
<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery
$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);
Somtimes i have to remove attribute checked from inputs type="radio" :
let el = document.getElementById('your_input_id');
el.checked = false;
el.removeAttribute('checked');
<form>
<input type="radio" name="btn"> Item1
<input type="radio" name="btn"> Item2<br>
<input type="reset">
</form>
This could work..

Categories

Resources