How to check radio button is checked using JQuery? - javascript

I have two radio buttons in one group, I want to check the radio button is checked or not using JQuery, How ?

Given a group of radio buttons:
<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">
You can test whether a specific one is checked using jQuery as follows:
if ($("#radio1").prop("checked")) {
// do something
}
// OR
if ($("#radio1").is(":checked")) {
// do something
}
// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))
You can get the value of the currently checked one in the group as follows:
$("input[name='radioGroup']:checked").val()

//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});

This is best practice
$("input[name='radioGroup']:checked").val()

jQuery 3.3.1
if (typeof $("input[name='yourRadioName']:checked").val() === "undefined") {
alert('is not selected');
}else{
alert('is selected');
}

Radio buttons are,
<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">
to check on click,
$('.radioButtons').click(function(){
if($("#radio_1")[0].checked){
//logic here
}
});

Check this one out, too:
$(document).ready(function() {
if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) {
//its checked
}
});

Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:
if ($('input[name="yourRadioNames"]:checked').val()){ (checked) or if (!$('input[name="yourRadioNames"]:checked').val()){ (not checked)

Try this:
var count =0;
$('input[name="radioGroup"]').each(function(){
if (this.checked)
{
count++;
}
});
If any of radio button checked than you will get 1

Simply you can check the property.
if( $("input[name='radioButtonName']").prop('checked') ){
//implement your logic
}else{
//do something else as radio not checked
}

Related

how to show checkbox as checked in jquery

enter image description here
$(document).ready(function() {
$('.editbtn').on('click', function(){
$('#editmodal').modal('show');
$tr=$(this).closest('tr');
var data= $tr.children("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#update_id').val(data[0]);
$('#finame').val(data[1]);
$('#liname').val(data[2]);
$('#Eimail').val(data[3]);
$('#ContactNumber').val(data[4]);
$('#Giender').val(data[5]);
$('#Dob').val(data[6]);
$('#addriess').val(data[7]);
$('#Ciity').val(data[8]);
$('#pinicode').val(data[9]);
$('#stiate').val(data[10]);
$('#countiry').val(data[11]);
$('#HobbyiDrawing').each(function(){ this.checked = true; });
$('#HobbyiDrawing').each(function(){ this.checked = false; });
// $('#HobbyiDrawing').attr('checked', true);
$('#HighiSchool').val(data[13]);
});
});
i want to checkbox and radio button as checked in update modal form how to resolve it please guide me
$('#HobbyiDrawing').attr("checked",true);
You can do it like this.
try checked attribute in both input tags as give down
<input type="radio" name="color" value="red" checked>
<input type="checkbox" checked>
You can use this construction for check all checkbox via JQuery
onclick="$('input[name*=\'selected\']').prop('checked', this.checked);"
For radio buttons you can use those methods - How to set radio button status with JavaScript
Set your dynamic value in values variable to checked checkbox or
radio
$('input[value='+values+'').attr('checked', true);

How to check if radio button is selected or not? [duplicate]

I have two radio buttons and that needs to fire a event according to what radio button is selected. Problem is that it fires immediately and doesn't let the user select an option. How I can get the user's input first and then run the JavaScript.
Here is the code:
if (document.getElementById("radio_myself").checked == true) {
alert(document.getElementById("radio_myself").value);
} else {
alert(document.getElementById("radio_selse").value);
}
<span><input id="radio_myself" name="radMyself" type="radio" value="Myself"/>Myself</span>
<span><input id="radio_selse" name="radSelse" type="radio" value="Someone"/>Someone Else</span>
This will make them select one first by using a function on change. By giving them the same name only one at a time can be selected, this will let you return the correct value.
From Chris's comment Also == true is redundant and can be removed, because checked is a boolean.
function check() {
if (document.getElementById("radio_myself").checked) {
alert(document.getElementById("radio_myself").value);
} else {
alert(document.getElementById("radio_selse").value);
}
}
addEventListener("change", ({target}) => { if(target.matches("input[type='radio']")){ check(); } })
<span><input id="radio_myself" name="radSelse" type="radio" value="Myself"/>Myself</span>
<span><input id="radio_selse" name="radSelse" type="radio" value="Someone"/>Someone Else</span>

detect selections of 2 sets of radio buttons in jquery

I have a web page which asks the user two simple yes-no questions. Under each question there's a set of two radio buttons in which the user can choose either yes or no.
<p>Question 1 yes or no?</p>
<input type="radio" name="q1" id="q1-y" value="Yes">Yes
<input type="radio" name="q1" id="q1-n" value="No">No
<p>Question 2 yes or no?</p>
<input type="radio" name="q2" id="q2-y" value="Yes">Yes
<input type="radio" name="q2" id="q2-n" value="No">No
If the user chooses yes for BOTH questions, it needs to display some HTML which will provide a link to a certain page. If the users answers no to one or both of the questions, then some alternative HTML will appear which will display another message.
There can't be a submit button like a form and this has to be a javascript/jquery based solution, not server side. The page needs to:
1) Detect when both sets of questions have been answered. Then
2) Instantly display certain HTML depending on if either a) YES has been answered to both, or b) if a NO has been given once or more.
Essentially, the logic should be something along the lines of:
if( /*both radio buttons answered*/ ){
if( /*both answers are yes*/ ){
/*show HTML set 1*/
} else {
/*show HTML set 2*/
}
}
I have tried looking at questions on this site, but I can't seem to find a solution to this specific problem. Let me know if anything needs clarifying.
Thanks very much!
Different solution:
$( "input" ).change(function() {
var buttons = jQuery("input:radio:checked").get();
var values = $.map(buttons, function(element) {
return $(element).attr("value");
});
if(values == "Yes,Yes") {
alert("both yes");
}
else {
//do something else
}
});
Demo: Multiple Radiobuttons
Don't like to check the string like that but could be adjusted in a proper way.
Try this:
$(document).ready(function(){
$("#yep").hide();
$("#nope").hide();
$(".nones").click(function(){
$("#yep").hide();
$("#nope").show();
});
$(".yipis").click(function(){
var checkeo = 1;
$( ".yipis" ).each(function( index ) {
if($(this).is(":checked") == false)
{
checkeo = 0;
};
});
if(checkeo){
$("#nope").hide();
$("#yep").show();
}
});
});
Working fiddle: http://jsfiddle.net/robertrozas/84o46mqd/
Here is a possible way to access the values you want. JSFiddle
HTML
<p>Question 1 yes or no?</p>
<input type="radio" name="q1" id="q1-y" value="Yes">Yes
<input type="radio" name="q1" id="q1-n" value="No">No
<p>Question 2 yes or no?</p>
<input type="radio" name="q2" id="q2-y" value="Yes">Yes
<input type="radio" name="q2" id="q2-n" value="No">No
<p>
<input type="button" id="finished" value="Submit" />
</p>
<div id="htmlarea"></div>
JavaScript
I find that jQuery is() function and the pseudo class :checked are helped when reading radio buttons.
$("#finished").click(function() {
var q1y = $("#q1-y").is(":checked");
var q1n = $("#q1-n").is(":checked");
var q2y = $("#q2-y").is(":checked");
var q2n = $("#q2-n").is(":checked");
if (q1y && q2y) {
$("#htmlarea").html("Both yes");
} else if (q1n && q2n) {
$("#htmlarea").html("Both no");
} else {
var html = "";
if (q1y) html += "Q1 yes. ";
if (q1n) html += "Q1 no. ";
if (q2y) html += "Q2 yes. ";
if (q2n) html += "Q2 no. ";
if (html=="") html = "None selected";
$("#htmlarea").html(html);
}
});
Instead of setting the HTML text, use window.location.href = "http://someurl.com"; if you want to redirect to another webpage.
One approach, given the following HTML (note the custom data-* attributes in the appended <div> elements, used to identify which choice those elements relate to):
<p>Question 1 yes or no?</p>
<input type="radio" name="q1" id="q1-y" value="Yes" />Yes
<input type="radio" name="q1" id="q1-n" value="No" />No
<p>Question 2 yes or no?</p>
<input type="radio" name="q2" id="q2-y" value="Yes" />Yes
<input type="radio" name="q2" id="q2-n" value="No" />No
<div class="result" data-relatesTo="Yes">All choices are 'yes'</div>
<div class="result" data-relatesTo="No">All choices are 'no'</div>
Which works with the following jQuery:
// caching the radio elements on the page:
var radios = $('input[type="radio"]'),
// getting the number of unique radio 'groups':
radioGroups = $.unique($('input[type="radio"]').map(function () {
return this.name;
}).get());
// binding an anonymous function as a change-event handler:
radios.change(function () {
// getting all the checked radio inputs:
var checked = radios.filter(':checked'),
// creating an object that maps to the relevant values/choices to be made:
choice = {
'yes': checked.filter(function () {
return this.value.toLowerCase() === 'yes';
}).get(),
'no': checked.filter(function () {
return this.value.toLowerCase() === 'no';
}).get()
};
// if all groups have a checked radio input:
if (checked.length === radioGroups.length) {
// iterate over the '.result' div elements:
$('div.result').each(function (i, el) {
// using 'toggle(switch)' to show/hide the element,
// the switch tests whether the choice related to the current
// element is equal to the number of radioGroups. If it is,
// it's shown, otherwise it's hidden.
$(this).toggle(choice[el.getAttribute('data-relatesTo').toLowerCase()].length === radioGroups.length);
});
}
});
JS Fiddle demo.
Alternatively, with the same HTML, the following jQuery approach also works:
var radios = $('input[type="radio"]'),
radioGroups = $.unique($('input[type="radio"]').map(function () {
return this.name;
}).get());
radios.change(function () {
var checked = radios.filter(':checked'),
// getting all the unique chosen values (in lowercase):
opts = $.unique(checked.map(function(){
return this.value.toLowerCase();
}).get());
if (checked.length === radioGroups.length) {
// hide all the '.result' elements:
$('div.result').hide()
// filter the 'div.result' elements:
.filter(function(){
// if the number of opts (chosen values) is 1
// (all choices are the same) and the 'data-relatesTo' attribute
// of the current element we're filtering is equal to that single
// option, then the element is retained in the selector
return opts.length === 1 && this.getAttribute('data-relatesTo').toLowerCase() === opts[0].toLowerCase();
})
// and so we show it:
.show();
}
});
JS Fiddle demo.
References:
JavaScript:
Element.getAttribute().
String.prototype.toLowerCase().
jQuery:
$.unique().
each().
filter().
get().
hide().
map().
show().
toggle().

How can I toggle radiobutton

Say this is my HTML:
<input type="radio" name="rad" id="Radio0" checked="checked" />
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />
As you can see the 1st radio button is checked. I need the radio button to function like toggle. For eg. If I again click on radio0, all radio buttons should be unchecked.
How can I achieve that?
Update: I don't want any extra buttons. For eg. I could add a button and set the checked property for all radio buttons to be false. However, I don't want that. I only want my form to consist of these 4 radio buttons.
Update: Since most of the people don't understand what I want, let me try to rephrase- I want the radio button to function in toggle mode. I've given the same name to all radio buttons hence it's a group. Now I want the radiobuttons to toggle itself. Eg. if I click on radio0, it should get unchecked if it's checked and checked if it's unchecked.
The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});
You will also need to add this attribute to the initially checked radio markup
<input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/
Once you give the name of 2 or more radio buttons as the same, they automatically become a group. In that group only one radio button can be checked. You have already achieved this.
This code solved my issue
$("[type='radio']").on('click', function (e) {
var previousValue = $(this).attr('previousValue');
if (previousValue == 'true') {
this.checked = false;
$(this).attr('previousValue', this.checked);
}
else {
this.checked = true;
$(this).attr('previousValue', this.checked);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label >Toogle radio button example</label>
<br />
<input type="radio" name="toogle_me" value="mango"> Blue </input>
<input type="radio" name="toogle_me" value="kiwi"> Green </input>
<input type="radio" name="toogle_me" value="banana"> Yellow </input>
<input type="radio" name="toogle_me" value="orange"> Orange </input>
I use an onClick() like the following for my custom radios:
$(function(){
// if selected already, deselect
if ($(this).hasClass('selected') {
$(this).prop('checked', false);
$(this).removeClass('selected');
}
// else select
else {
$(this).prop('checked', true);
$(this).addClass('selected');
}
// deselect sibling inputs
$(this).siblings('input').prop('checked', false);
$(this).siblings('input').removeClass('selected');
}
Using #Goran Mottram answer just tweaking it a bit to suit the case where radio buttons are not siblings.
$(".accordian-radio-button").click(function(){
var wasChecked = true;
if($(this).data('waschecked') == true){
$(this).prop('checked', false);
wasChecked = false;
}
$('input[name="ac"]').data('waschecked', false);
$(this).data('waschecked', wasChecked);
})
<input class="accordian-radio-button" data-waschecked="false" type="radio" name="ac" id="a1" />
I ran into this as well, after thinking about it and playing around with the various fiddles offered, I had a few dissatisfactions with the offered solutions.
My main problem was the last line of the accepted answer, requiring a reset:
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
And since I'm not using jQuery, I'd have to loop over and evaluate the siblings myself, which isn't a huge deal, but seemed inelegant to me. But, there's no way around it with that method, because you're using the dataset as a storage of information.
After playing around, I realized is that the problem is that when a radio is clicked, it triggers the clicked event, and whatever function is attached to that click event completes itself before the function for the "onchange" event is ever evaluated, let alone called. So, if the click event "unchecks" the toggle, then no change event is ever fired.
I've left my failed attempt here:
https://codepen.io/RiverRockMedical/pen/daMGVJ
But, if you could answer the question "will a change event happen after this click event?" then you could get a toggle working.
The solution I came up with can be seen at this pen:
https://codepen.io/RiverRockMedical/pen/VgvdrY
But basically is as follows:
function onClick(e) {
e.dataset.toDo = 'uncheck';
setTimeout(uncheck, 1, {
event:'click',
id:e.id,
dataset:e.dataset
});
}
So, on the click event, set a marker that the click has happened, and the use setTimeout() to create a pause that allows the onchange event to be evaluated and fire.
function onChange(e) {
e.dataset.toDo = 'leave';
}
If the onchange event fires, it undoes what was done by the onclick event.
function uncheck(radio) {
log('|');
if (radio.event !== 'click') return;
log('uncheck');
if (radio.dataset.toDo === 'uncheck') {
document.getElementById(radio.id).checked = false;
radio.checked = false;
}
}
Then, when the uncheck function starts, it has the information of whether a change event followed the click event or not. If not, then the radio is unchecked, and functions as a toggle.
And, it's basically self-resetting, so I don't have to loop over all the radios and reset their datasets to the initial values at the end of the function.
Now, I'm sure there's a cooler async/await way to do this that doesn't use setTimeout and would be even more elegant, but I'm still learning and I couldn't come up with it. Anyone else?
<input type="radio" name="gender" id="male"onclick="getChecked(1)"><label for="male">Male</label>
<input type="radio" name="gender" id="female"onclick="getChecked(2)"><label for="female">female</label>
<script>
var btnChecked = "";
function getChecked(i) {
if(btnChecked == i) {
btnChecked = "";
document.getElementsByTagName("input")[i-1].checked = false;
}
else btnChecked = i;
}
</script>
A simple approach in jQuery (even though I don't use jQuery nowdays):
function makeRadioInputsToggleable(radioInputs){
let radioGroup = {
lastValue: radioInputs.filter(':checked').prop('value'),
get value(){
return this.lastValue;
},
set value(v){
let inputToCheck = radioInputs.filter((i, el) => el.value === v);
radioInputs.filter(':checked').prop('checked', false);
if(inputToCheck.length > 0){
inputToCheck.prop('checked', true);
this.lastValue = v;
}else{
this.lastValue = undefined;
}
},
};
radioInputs.on('click', (e) => {
let input = e.target;
if(input.value === radioGroup.lastValue){
input.checked = false;
radioGroup.lastValue = undefined;
}else{
radioGroup.lastValue = input.value;
}
}).on('keydown', (e) => {
if(e.code === 'Space'){
let input = e.target;
if(input.checked){
input.checked = false;
input.blur();
radioGroup.lastValue = undefined;
}
}
});
return radioGroup;
}
let radioInputs = $('input[type="radio"][name="rad"]');
let radioGroup = makeRadioInputsToggleable(radioInputs);
$('.check-radio').on('click', (e)=>{
let value = e.target.value;
radioGroup.value = value;
});
// Note:
// 1. pass a single group of radio inputs to `makeRadioInputsToggleable`
// 2. set distinct values for each radio input in a group.
// 3. to change checked radio programmatically, use `radioGroup.value = 'XXX'` rather than radioInputs.prop('checked', false).filter('[value="XXX"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>makeRadioInputsToggleable</h3>
<label><input type="radio" name="rad" value="1" id="Radio0" checked="checked" />1</label>
<label><input type="radio" name="rad" value="2" id="Radio1" />2</label>
<label><input type="radio" name="rad" value="3" id="Radio2" />3</label>
<label><input type="radio" name="rad" value="4" id="Radio4" />4</label>
<label><input type="radio" name="rad" value="5" id="Radio3" />5</label>
<p>1. click on an already-checked radio button, the radio will be toggled to unchecked.</p>
<p>2. focus on an already-checked radio button and press 'Space', the radio will be toggled to unchecked. <i>(This may not work in Code Snippet result area)</i></p>
<p>
3. programmatically
<button class="check-radio" value="2">check radio with value 2</button>
<button class="check-radio" value="10">check radio with value 10</button>
</p>

Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?
I am using the following code, but it always returns the count of checked checkboxes regardless of id.
function isCheckedById(id) {
alert(id);
var checked = $("input[#id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
$('#' + id).is(":checked")
That gets if the checkbox is checked.
For an array of checkboxes with the same name you can get the list of checked ones by:
var $boxes = $('input[name=thename]:checked');
Then to loop through them and see what's checked you can do:
$boxes.each(function(){
// Do stuff here with this
});
To find how many are checked you can do:
$boxes.length;
IDs must be unique in your document, meaning that you shouldn't do this:
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
Instead, drop the ID, and then select them by name, or by a containing element:
<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
And now the jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
$('#checkbox').is(':checked');
The above code returns true if the checkbox is checked or false if not.
All following methods are useful:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked
It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.
jQuery code to check whether the checkbox is checked or not:
if($('input[name="checkBoxName"]').is(':checked'))
{
// checked
}else
{
// unchecked
}
Alternatively:
if($('input[name="checkBoxName"]:checked'))
{
// checked
}else{
// unchecked
}
The most important concept to remember about the checked attribute is
that it does not correspond to the checked property. The attribute
actually corresponds to the defaultChecked property and should be used
only to set the initial value of the checkbox. The checked attribute
value does not change with the state of the checkbox, while the
checked property does. Therefore, the cross-browser-compatible way to
determine if a checkbox is checked is to use the property
All below methods are possible
elem.checked
$(elem).prop("checked")
$(elem).is(":checked")
This is also an idea I use frequently:
var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;
If cheked, it'll return 1; otherwise it'll return 0.
You can use this code,
if($("#checkboxId").is(':checked')){
// Code in the case checkbox is checked.
} else {
// Code in the case checkbox is NOT checked.
}
As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)
<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />
Example 1 - With checked
$("#test-with-checked").on("click", function(){
if(mycheckbox.checked) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 2 - With jQuery is, NOTE - :checked
var check;
$("#test-with-is").on("click", function(){
check = $("#mycheckbox").is(":checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 3 - With jQuery prop
var check;
$("#test-with-prop").on("click", function(){
check = $("#mycheckbox").prop("checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Check Working jsfiddle
I know the OP want jquery but in my case pure JS was the answer so if anyone like me is here and do not have jquery or do not want to use it - here is the JS answer:
document.getElementById("myCheck").checked
It returns true if the input with ID myCheck is checked and false if it is not checked.
Simple as that.
You can try this:
<script>
function checkAllCheckBox(value)
{
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
}
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
You can use any of the following recommended codes by jquery.
if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};
You can do it simply like;
Working Fiddle
HTML
<input id="checkbox" type="checkbox" />
jQuery
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
or even simpler;
$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");
If the checkbox is checked it will return true otherwise undefined
$(document).on('click','#checkBoxId',function(){
var isChecked = $(this).is(':checked');
console.log(isChecked);
});
This code above works also on bootstrap modal. isChecked is true or flase ;
Simple Demo for checking and setting a check box.
jsfiddle!
$('.attr-value-name').click(function() {
if($(this).parent().find('input[type="checkbox"]').is(':checked'))
{
$(this).parent().find('input[type="checkbox"]').prop('checked', false);
}
else
{
$(this).parent().find('input[type="checkbox"]').prop('checked', true);
}
});
Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.
In the end
<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">
var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');
This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.
Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!
Here are the syntaxes :
var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
/* The DOM way - The fastest */
if(checkbox[0].checked == true)
alert('Checkbox is checked!!');
/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
alert('Checkbox is checked!!');
/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
alert('Checkbox is checked!!');
I personally prefer .prop(). Unlike .is(), It can also be used to set the value.
Something like this can help
togglecheckBoxs = function( objCheckBox ) {
var boolAllChecked = true;
if( false == objCheckBox.checked ) {
$('#checkAll').prop( 'checked',false );
} else {
$( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
if( false == chkbox.checked ) {
$('#checkAll').prop( 'checked',false );
boolAllChecked = false;
}
});
if( true == boolAllChecked ) {
$('#checkAll').prop( 'checked',true );
}
}
}
Try this...
$(function(){
$('body').on('click','.checkbox',function(e){
if($(this).is(':checked')){
console.log('Checked')
} else {
console.log('Unchecked')
}
})
})
Toggle checkbox checked
$("#checkall").click(function(){
$("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes.
Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
Your question is not clear: you want to give "checkbox array id" at input and get true/false at output - in this way you will not know which checkbox was checked (as your function name suggest). So below there is my proposition of body of your isCheckedById which on input take checkbox id and on output return true/false (it's very simple but your ID should not be keyword),
this[id].checked
function isCheckedById(id) {
return this[id].checked;
}
// TEST
function check() {
console.clear()
console.log('1',isCheckedById("myCheckbox1"));
console.log('2',isCheckedById("myCheckbox2"));
console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
You can try either any of the ways preferred, as in jQuery or JavaScript.
Get the value as below and assign to the variable then you if-else statements as per your requirement.
var getVal=$('#checkbox_id').is(":checked"); // jQuery
var getVal=document.getElementById("checkbox_id").checked //JavaScript
if (getVal==true) {
// perform task
} else {
// perform task
}
use code below
<script>
$(document).ready(function () {
$("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}
function ShowMailSection() {
if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
$("[id$='SecEmail']").removeClass("Hide");
}
</script>

Categories