Why isn't jquery detecting when a radio button is unchecked? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery $(#radioButton).change(…) not firing during de-selection
I have the following HTML/jQuery:
<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">
$("#rb2").change(function () {
if ($(this).is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
When my rb2 radio button is unselected by selecting rb1, the change event does not fire. Why is this? Is it possible to get this working without changing my selector to match both inputs and then looking at the ID?
Fiddle: http://jsfiddle.net/4uRWR/

The change event only gets sent when you actually modify the item itself. When you click the other radio, you aren't modifying it. A fix would be to watch the change event on every input:radio, then just check the state of the relevant radio button:
$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
http://codepen.io/AlienHoboken/pen/akwjB

Listen for change on every input related to your group of radios and then check if a specific one is selected.
$("input[name=rb]").change(function () {
if ($('#rb2').is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
http://jsfiddle.net/4uRWR/2/

You can artificially trigger a "change" on radio buttons from the same group so that the original bound handler would get picked up and output "unchecked". The trick is to avoid being stuck in an infinite loop by recursively re-triggering the event, we can avoid that by ignoring artificial events that lack the originalEvent property:
$("input[type=radio]").on("change", function (e) {
var $this = $(this);
//all inputs with the same name
var $targetInputSelector = $("input[name=" + $this.attr("name") + "]");
//check if the handler was fired "naturally"
//if yes, trigger the change handler "artificially" for inputs with the same name
if (e.hasOwnProperty('originalEvent')) {
//exclude the element that was changed "naturally"
//from the subset of all the elements with the same name
$targetInputSelector.not($this).triggerHandler("change");
}
});
This code works when added on top of your current handler and satisfies the without changing my selector to match both inputs and then looking at the ID criteria ;)
http://jsfiddle.net/a73tn/24/

I sorta ran into this issue a few days ago. Instead of listening for an individual click on a radio button, I listen for a click on the <ul> I have them in and then call this function to check if one has been selected.
// Iterate over the radio group and determine if one of them is selected
function loopRadBtns(btnGroup)
{
var isChecked = false;
btnGroup.find('input[type="radio"]').each(function()
{
if($(this).attr('checked'))
{
isChecked = true;
}
});
return isChecked;
}

Related

How to check if a checkbox is checked when programmatically added? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 months ago.
Is there a way to check if a checkbox is checked when you programmatically add another checkbox? For example, if I have a function that adds a checkbox and then it's checked and then add another checkbox, the second checkbox determines if the first checkbox is selected or not. If the first checkbox is selected, don't show the second added checkbox. If the first checkbox is not selected, you can check the second checkbox and the first one is hidden.
The code I have below is suppose to hide any checkbox that's added after the first checkbox is selected.
$(document).on( "click", '.add', function() {
// programmatically add checkboxes
$('.add').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div><div class='add2'>+add</div>").remove();
});
$(document).on( "click", '.add2', function() {
$('.add2').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div>").remove();
});
// function to check is checkboxes are selected
if ($("#cover_photo_set_featured input").is(':checked')) {
$('#cover_photo_set_featured input[type=checkbox]').each(function() {
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false) {
//Hide the choice
$(this).parent().hide();
}
});
} else {
$('#cover_photo_set_featured input[type=checkbox]').parent().show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add">+add</div>
In javascript you can only add events to elements already on the DOM.
To achive what you want. you have to reassign events everytime you add a checkbox.
I would recommend adding a function that adds event listeners like so:
function setup() {
if ($("#cover_photo_set_featured input").is(':checked')) {
$('#cover_photo_set_featured input[type=checkbox]').each(function() {
//Check if the box is checked
var x = $(this).is(':checked');
//if checkbox is NOT checked
if(x === false) {
//Hide the choice
$(this).parent().hide();
}
});
} else {
$('#cover_photo_set_featured input[type=checkbox]').parent().show();
}
}
then calling it whenever you add a new checkbox.

How to uncheck the checkbox of a jquery table when changing a combobox?

I have the following question, when I change the value of the combobox, the checkboxes are still marked, with prop the values are unmarked, but this time it does not work, the idea is to reset the marked checkboxes when the value of the checkbox is changed.
Regards.
var cambio = $("#cmbKit").on('change', function () {
var checkPoint = !$(this).data('checked');
$('#tblCajas input[type="checkbox"]').each(function () {
if (checkPoint == true) {
$(':checkbox').prop('checked', false);
$("input[type='checkbox']").prop('checked', false);
}
});
});
if (cambio) {
selectedBox = 0;
$('#divCalculos').hide();
$('#btnPlanificar').hide();
}
As you want to reset every checkbox on change event of combobox, you can use below code -
$("#cmbKit").change(function() {
$("input[type='checkbox']").prop('checked', false);
});
You shouldn't use any if condition as you are going to reset it after every change event.
Please note that given code will reset all checkboxes on page, add table selector as well in case you have multiple table with different content.
Hope this helps.

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

JS with select boxes

I am currently working on a bit of javascript that will execute when a checkbox is checked.
When the checkbox is checked, the form will display 2 more select boxes.
I've attempted something but i'm not very good with javascript, can someone take a look and lemme know where i'm going wrong?
$(document).ready(function() {
$("#repeat").change(function () {
if ($("#repeat").checked){
$("#numbers").slideDown();
} else{
$("#numbers").slideUp();
}
});
$("#numbers").hide();
$("#repeat").tigger("change");
});
And the id of the checkbox is repeat and id of one of the select boxes is numbers.
This part is not correct:
$("#repeat").checked
and should be
this.checked
So whole script:
$(document).ready(function () {
$("#repeat").change(function () {
if (this.checked) {
$("#numbers").slideDown();
} else {
$("#numbers").slideUp();
}
});
$("#numbers").hide();
$("#repeat").trigger("change"); // <--- trigger, not tigger
});
$("#repeat") is a jQuery instance object, it doesn't have a property checked. However this inside of change event handler refers to the HTMLSelectElement which has this property.
Also it's trigger not tigger.

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

Categories

Resources