How to implement a click event on mutually exclusive checkboxes in jQuery? - javascript

I have two checkboxes:
<input id="outside" type="checkbox" value="1" data-gid="41820122" />
<input id="inside" type="checkbox" value="1" data-gid="41820122" />
I've made them mutually exclusive with:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
});
});
This works fine. But I also want to add additional click functionality to the 'inside' checkbox. I want it to enable/disable a textarea on the same form, so I've done this:
$('#application_inside').click(function() {
if ($(this).is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
});
So, if the 'inside' checkbox is checked, the textarea will be enabled, if it's not checked, the textarea should be disabled.
The problem is that if the 'inside' checkbox is checked, and the user then checks the 'outside' checkbox, the 'inside' becomes unchecked (as it should be), but the textarea remains enabled. This appears to be because the 'inside' checkbox was never actually clicked by the user.
I've tried working around this with the following:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
checkboxes.triggerHandler("click"); //new code to fire any click code associated with unchecked boxes
});
});
But this just throws the browser in a loop, since the two different click events end up calling each other.
How can I keep my mutually exclusive code while still allowing the enable/disable code for the 'inside' checkbox to work?

You can create a custom event that you trigger when you click on #application_inside. Also you will fire this custom event when you uncheck other boxes because of the exclusiveness.
Here is an example: http://jsfiddle.net/gs78t/2/

you may try something like this
var insideChanged = function() {
if ($('#inside').is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
};
$('#application_inside').click(insideChanged);
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
insideChanged(); //new code to fire any click code associated with unchecked boxes
});
});

Related

JavaScript to detect what checkboxes and checked and perform action

I have a jsp page with a checkbox declared like so
<form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" />
it is contained within a for loop and basically a checkbox is displayed for each session. That all works fine and I have no issues.
currently when a check box is checked this function is ran
$("input[id*='checkbox_']").each(function () {
$(this).click(function(){
var dataid = $(this).attr("data-id");
var divId = "fullAttendence_" + dataid;
var divIdAttendee = "attendeeType_" + dataid;
$('#' + divId).toggle(this.checked);
$('#' + divIdAttendee).toggle(this.checked);
});
});
This then results in some other checkboxes being checked and some divs that were hidden being shown.
I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked.
I have that part working but I can't get the function to run properly.
I have the following
if ($("input[id*='checkbox_']").is(':checked')) {
var dataid = $(this).attr("data-id");
var divId = "fullAttendence_" + dataid;
var divIdAttendee = "attendeeType_" + dataid;
$('#' + divId).toggle(this.checked);
$('#' + divIdAttendee).toggle(this.checked);
}
This function DOES get called as I tested it with a console.log.
the issue is that
var dataid = $(this).attr("data-id");
comes back as
undefined
Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was?
any help is really appreciated.
if ($("input[id*='checkbox_']").is(':checked')) {
... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct:
$("input[id*='checkbox_']").each(function() {
if ($(this).is(':checked')) {
// do something
}
});

'Checkbox change' results in infinite loop

My requirement is to check/uncheck all other checkboxes on a checkbox change event
But results in infinite loop.
$(".chk").change(function(event) {
var $this = $(this);
var id = $this.attr('id');
var chkOtherCheckboxes = 'on';
if ($this.is(':checked')) {
chkOtherCheckboxes = 'off';
}
$('input:checkbox:not("#' + id + '")').bootstrapToggle(chkOtherCheckboxes);
});
Disable bootstrapToggle and change input, then enable it again.
$(".chk").change(function(event) {
var id = this.id;
var status = !this.checked;
$('input:checkbox:not("#' + id + '")').each(function(){
$(this).bootstrapToggle('destroy');
$(this).prop('checked', status);
$(this).bootstrapToggle();
});
});
You're changing the same checkbox again .chk when user clicks on checkbox.
User click checkbox --> triggers change function -->
--> changes status of checkboxes( including itself) -->
--> again triggers change function
//infinite loop
Make sure you don't trigger change for the current checkbox.
Let me know if it helps.

On change select, if item has the same value in dropdown check the checkbox

I am creating a dynamic dropdown list out of checkboxes. What I want is when the dropdown changes (on select) I want it to check the checkboxes with the same values or perhaps with the same name? I also want it to do vice versa, if you check a checkbox the select dropdown should change as well.
Here is my codepen - http://codepen.io/BryanBarrera/pen/QEXVxY
I am having issues writing this. Here is what I have. What is the best approach for this? How do I match up elements to change or check the checkboxes?
Any idea or suggestions would be much apprecated
"use strict";
var checkBoxes = $('.form-item'),
checkBox = $('input[type="checkbox"]'),
$select = $('<select></select>').appendTo('body').wrap('<div class="select-dropdown"></div>');
checkBoxes.each(function (n) {
var dataText = $(this).find('label').text();
var dataValue = $(this).find('input').val();
$select.append('<option value="' + dataValue + '">' + dataText + '</option>');
});
$select.on('change', function(){
var checkboxvalue = $(this).val();
var a = $(this).filter(function(){return this.value=='checkboxvalue'});
console.log(a);
console.log(checkboxvalue);
if (checkboxvalue == $(this).val() ) {
// alert('yup');
}
});
This will do the trick:
$select.on('change', function(){
var checkboxvalue = $(this).val();
$('input[value='+checkboxvalue+']').prop('checked', true);
});
checkBox.on('change', function(){
var selectValue = $(this).val();
$select.val(selectValue)
});
You probably want some other function to handle multiple selection, because you dropdown obviosly don't support multiple selection like checkboxes.
Example
You're setting the value of the checkbox element, but not actually checking the box. You also need to do this:
$('#checkbox-selector').prop('checked', true);

Check/uncheck input not working

If you click on buton it opens 3 checkbox (one that selects it all and two subinputs).
What I'm trying to do is that if the user clicks for example on Centro de dia the input remains checked and the other (buton in this case) gets unchecked. If the user clicks on buton the other gets unchecked, and if the user clicks on Check/uncheck all it obviously checks all or uncheck them all.
But right now if I click on one of the subinputs, it checks/unchecks but doesn't affect the other one.
This is the code i'm using:
$check_all = $('<label></label>')
.text(GeoMashup.opts.check_all_label)
.prop('for', 'gm-' + taxonomy + '-check-all')
.prepend(
$('<input type="checkbox" />').prop('id', 'gm-' + taxonomy + '-check-all')
.prop('checked', (default_off ? false : 'checked'))
.change(function () {
if ($(this).is(':checked')) {
$legend.find('input.gm-' + taxonomy + '-checkbox:not(:checked)').click();
} else {
$legend.find('input.gm-' + taxonomy + '-checkbox:checked').click();
}
})
Any ideas how to make it work that way?
You can use .prop() instead of .attr() if using Jquery 1.6 and above.

I need an event trigger for a radio button for when it is unchecked because another button is checked

I need an event trigger for a radio button for when it is unchecked because another button is checked.
The code below should demonstrate my dilemma.
If you will notice, there is an onchange event trigger atttached to each radio button and checkbox in the html code. In theory a change in state from checked to unchecked should fire the onchange event.
This happens as expected with the check boxes. If you check one, you get the alert, 'Your item is changed to checked'. If you uncheck it, you get the alert, 'Your item is changed to unchecked'.
With the radio buttons, when you check button one, you get, as expected, the alert, 'Your item is changed to checked' since the button changed from unchecked to checked. However, when you check the second button and the first radio button is changed from checked to unchecked the "onchange" event trigger does not fire and the 'else' alert is not triggered.
So this issue for me is what event is triggered when a radio button gets unchecked by another button being checked?
I appreciate everyone's assistance on this.
--Kenoli
<html>
<head>
<title></title>
<script type="text/javascript">
function clickAction() {
//alert ('Your item changed');
if (this.checked == true) {alert ('Your item is changed to checked');}
else if (this.checked == false) {alert('Your item is changed to unchecked');}
}
</script>
<script type="text/javascript">
function initializeToggles() {
var button1= document.getElementById('button1');
button1.onchange = clickAction;
var box1= document.getElementById('box1');
box1.onchange = clickAction;
var box2= document.getElementById('box2');
box2.onchange = clickAction;
}
</script>
<script type="text/javascript">window.onload = initializeToggles;</script>
</head>
<body>
<input type="radio" name="testRadio" id="button1" >Button one<br/>
<input type="radio" name="testRadio" id="button2" >Button two<br/><br/>
<input type="checkbox" name="testCheckbox" id="box1" >Box one<br/>
<input type="checkbox" name="testCheckbox" id="box2" >Box two<br/><br/>
</body>
</html>
I came here looking for a quick solution for this type of problem, and nuc's answer helped me come up with this:
$(document).ready(function(){
$('input[type=radio]').change(function() {
var selected = $(this);
$('input[type=radio]').each(function() {
if $(this).attr('id') != selected.attr('id') {
console.log( $(this).attr('value') + ' was deselected because ' + selected.attr('value') + ' was clicked.')
}
});
});
});
There is no event for when a radio button gets unchecked. You might be able to use the onpropertychange event, however that's not a standardised event so it might only work in Internet Explorer.
The safest way would be to take care of that in the onchange event. If you want to know which radio button was unchecked, you would have to keep a reference to the currently checked element in a variable.
I slightly modified rthbound's code to handle a group of radio input's, in my case enclosed in a <table>. But this could easily altered for a <div>. Also this code is more compliant with jQuery 1.9. A common class would be better, to take the class from the selected radio and find other radio inputs with the same class, but I'm working with ASP.NET and this is quicker and easier for me.
$(document).ready(function(){
$(document).on("change", "input[type='radio']", function () {
var selected = $(this);
$(this).closest("table").find("input[type='radio']").each(function () {
if ($(this).attr("id") !== selected.attr("id")) {
console.log($(this).attr("value") + " was deselected because " + selected.attr("value") + " was clicked.");
}
});
});
});
I've solved this issue in a generic way:
whenever a radio button is changed:
if they were triggered by this system - we don't want unending loops.
find all its radio button friends
trigger change on them
then I can test for whether the radio button was checked or unchecked.
$(function(){
$('body').on('change', 'input[type="radio"]', function(e, by_other) {
if (!by_other) {
$("input[type='radio'][name='" + $(this).attr('name') + "']")
.not(this)
.trigger('change', true)
}
}
}
(I did translate it from coffeescript to javascript for ya'll.)
The Radio buttons have same name, so we can select them by name.
Because .change() is not effected when the radio is unchecked, so we use .click() instead of.
$('input[name="your-radio-name"]').click(function() {
var $radios = $('input[name="your-radio-name"]');
for (var i = 0; i < $radios.length; i++) {
var radio = $radios[i];
if (radio != this) {
radio = $(radio);
// Process for unchecked radios here
}
}
// Now, process for checked radio
// alert(this.value + ' is checked'); Or
alert($(this).val() + ' is checked');
});

Categories

Resources