jQuery unbinding click event on a radio button that is already selected - javascript

I am trying to create some parametric filters but i do not want to invoke the function that makes my search AJAX call when a radio button filter is already selected.
$('#contentType input:enabled').bind('click', function(e){
var $this = $(this),
$type = this.type,
$id = this.id;
if ($type === 'radio') {
if ($id === 'allContent'){
sFrm.$boxes.attr({'checked': false});
sFrm.$specificRadio.attr({'disabled': true});
searchAjax();
removeFilter();
}
} else if ($type === 'checkbox') {
if (sFrm.$boxes.filter(':checked').length === 0) {
sFrm.$allRadio.trigger('click');
} else {
var filterConfig = {
index: $('.subFilter').index($this),
txt: jQuery.trim($this.parent().text())
}
sFrm.$allRadio.attr({'checked': false});
sFrm.$specificRadio.attr({'disabled': false, 'checked': true});
searchAjax();
if ($this.is(':checked')) {
addFilter(filterConfig);
} else {
removeFilter(filterConfig.index);
}
}
}
});
So the jQuery above looks at ALL enabled inputs in the collection and when a user clicks the allContent radio button the searchAjax function is invoked.
This is correct when said radio button is not already selected/checked. At the moment the function is still invoked when the button is selected and i would like to stop this behaviour but cannot figure out how?
EDIT
Not sure i explained correctly. Hopefully this jsFiddle will help:
http://jsfiddle.net/QsbRp/3/
Basically if All content types is checked already and is clicked when checked then searchAjax should not be invoked. It currently invokes the function.
When it is not checked and clicked then it should behave as it is now (disable sibling radio button and uncheck all associated checkboxes).

Add at the top of your handler:
if ($this.is(":checked")) {
return;
}
The event handler will return and not execute the rest of the function if the radio button is currently selected.

Related

First on-click on checkbox displays modal popup window. How can i make on-second-click unchecks the checkbox?

I am doing a popup window using Bootstrap modal that is triggered by the click of a checkbox in the main page. The popup window contains several textboxes for searching from the database based on user's input. Then after the input and the click of a search button, a table will display the data retrieved on the same popup window. Then, after the user chooses a row from the table, the chosen data will be displayed in their respective textboxes in the main page and the checkbox will be checked.
My plan is to uncheck the checkbox on a second click (thinking if the user suddenly decided to cancel their decision - checking the checkbox). I tried but it didn't uncheck the checkbox. Instead, the popup window comes out at every click of the checkbox and the checkbox won't uncheck anymore.
$('#inputNew').on('hidden.bs.modal', function (e) {
document.getElementById("inputNewCheckbox").checked = true;
document.getElementById("inputMother").style.display = 'block';
document.getElementById("inputMotherlabel").style.display = 'block';
var value = $('#myPopupInput1').val();
$('#inputMother').val(value);
$('#inputNew').modal('hide');
});
$('#inputNew').on('click', '#SearchMother', function () {
var value = $('#myPopupInput1').val();
$('#inputMother').val(value);
$('#inputNew').modal('hide');
});
if ($checkbox.data('waschecked') == true && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
$('#inputNewCheckbox').prop('checked', false);
}));
}
This is the checkbox input in the view page:
<input type="checkbox" name="inputNew" value="inputNew" id="inputNewCheckbox" data-toggle="modal" data-target="#inputNew" data-waschecked="false"> New
For the checkbox unchecking part, i also tried
if ($('#inputNewCheckbox').prop('checked', true) && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
document.getElementById("inputNewCheckbox").checked = false;
}));
}
But when i run, the checkbox is checked by default and unchecking doesn't work. Plus the modal popup window appears.
I also tried
if (document.getElementById("inputNewCheckbox").checked = true && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
document.getElementById("inputNewCheckbox").checked = false;
}));
}
Also same output as above code..can anyone help me out please? How can i fix this?
You're probably better off listening for a change event on the checkbox, and only showing your modal if the checkbox is checked:
$('#inputNewCheckbox').on('change', function(e){
var _this = $(this);
if(_this.is(':checked')){
/* show your modal */
}
});
See change - Event reference and the :checked pseudo-class on MDN.

Deselect a radio option

I'm using the bootstrap radio buttons and would like to allow deselection of a radio group. This can be done using an extra button (Fiddle). Instead of an extra button, however, I would like to deselect a selected radio option if the option is clicked when it's active.
I have tried this
$(".btn-group label").on("click", function(e) {
var clickedLabel = $(this);
if ($(clickedLabel).hasClass("active"))
{
// an active option was clicked => deselect it
$(clickedLabel).children("input:radio").prop("checked", false)
$(clickedLabel).removeClass("active");
}
}
)
but there seems to be a race condition: the event of clicking the label that I use seems to be used by bootstrap.js to set the clicked label option to "active". If I introduce a timeout, the class "active" is removed successfully:
$(".btn-group label").on("click", function(e) {
var clickedLabel = $(this);
if ($(clickedLabel).hasClass("active"))
{
setTimeout(function() {
// an active option was clicked => deselect it
$(clickedLabel).children("input:radio").prop("checked", false)
$(clickedLabel).removeClass("active");
}, 500)
}
}
)
How can I toggle a selected option successfully without using a timeout?? Thank you for help.
Instead of using two method's preventDefault & stopPropagation, use return false, will work same.
The difference is that return false; takes things a bit further in
that it also prevents that event from propagating (or "bubbling up")
the DOM. The you-may-not-know-this bit is that whenever an event
happens on an element, that event is triggered on every single parent
element as well.
$(".btn-group label").on("click", function(e) {
var clickedLabel = $(this);
if ($(clickedLabel).hasClass("active"))
{
// an active option was clicked => deselect it
$(clickedLabel).children("input:radio").prop("checked", false)
$(clickedLabel).removeClass("active");
return false;
}
});
After messing with your code in jsfiddle for a while I figured out that a combination of preventDefault() and stopPropagation() does the trick.
Here's a fiddle
and the code:
$(".btn-group label").on("click", function(e) {
var clickedLabel = $(this);
if ($(clickedLabel).hasClass("active"))
{
// an active option was clicked => deselect it
$(clickedLabel).children("input:radio").prop("checked", false)
$(clickedLabel).removeClass("active");
e.preventDefault();
e.stopPropagation();
}
}
);

Select All Checkboxes while keeping track of manual selects jquery

I've been using a simple select all script for checkboxes for a while now that looks something like this:
<span id="select">Select All</span>
with
$('#select').click(function(event) {
var $that = $(this);
$('.checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
It's fairly simple. It attaches to an onclick, loops through all the inputs with the class .checkbox and checks or unchecks them accordingly. However what I'd like to do now is make it a bit more user friendly adding the following functionality to it.
1) When the user click the link labeled "Select All" it should select all check boxes as normal, but then change the text to "Deselect All". Similarly, when the user clicks "Deselect All" the text would go back to "Select All".
2) If the users manually select all check boxes I'd like check for this scenario and update the text from Select All to Deselect All as well.
Your code is checking whether a <span> is :checked, which as far as I know is not possible. Perhaps I'm wrong, but in this answer I'll use a different approach to keeping track of that, a data attribute.
// initialize 'checked' property
$('#select').data('checked', false);
// make link control all checkboxes
$('#select').click(function(event) {
var $that = $(this);
var isChecked = ! $that.data('checked');
$that.data('checked', isChecked).html(isChecked ? 'Deselect All' : 'Select All');
$('.checkbox').prop('checked', isChecked);
});
// make checkboxes update link
$('.checkbox').change(function(event) {
var numChecked = $('.checkbox:checked').length;
if (numChecked === 0) {
$('#select').data('checked', false).html('Select All');
} else if (numChecked === $('.checkbox').length) {
$('#select').data('checked', true).html('Deselect All');
}
});
Not jquery, but here's what I'd do
var cb=document.getElementsByClassName('cb'); //get all the checkboxes
var selectAll=document.getElementById('selectAll'); //get select all button
function selectAllState(inputEle,selectAllEle){ //class to manage the states of the checkboxes
var state=1; //1 if button says select all, 0 otherwise;
var num=inputEle.length;
function allChecked(){ //see if all are checked
var x=0;
for(var i=0;i<num;i++){
if(inputEle[i].checked==true){
x+=1;
}
}
return x;
}
function handler(){ //if all checked or all unchecked, change select all button text
var y=allChecked()
if( y==num && state){
selectAllEle.innerHTML='Deselect All';
state=0;
} else if(y==0 && !state){
selectAllEle.innerHTML='Select All';
state=1;
}
}
for(var i=0;i<num;i++){
inputEle[i].addEventListener('change',handler); //listen for changes in checks
}
function checkAll(){ //function checks or unchecks all boxes
for(var i=0;i<num;i++){
inputEle[i].checked=state;
}
handler();
}
selectAll.addEventListener('click',checkAll); //listen for button click
}
var myState=new selectAllState(cb,selectAll); //instance the selectAllState class
This creates a javascript class to manage the states of all your checkboxes. It takes two arguments, the first being the array of checkboxes (which is what you get if you use getElementsByClassName), and the second being the select all button. The internal methods could be exposed using the this keyword if you want to be able to, for example, have a different part of the application select or deselect all the checkboxes.
Try breaking it down in several functions: Let's call the span toggle, as it can select and de-select all.
<span id="toggle">Select All</span>
And we'll have a function to select and de-select all of the values. No need to iterate through the list as prop sets the value for all elements
function SetAll(value){
$(".checkbox").prop("checked", value);
}
Then for the toggle button:
$("#toggle").click(function(){
if($(this).text() == "Select All"){
SetAll(true);
$(this).text("De-select All");
} else {
SetAll(false);
$(this).text("Select All");
}
});
Finally we need an onchange event for each checkbox:
$(".checkbox").change(function(){
var allCheckboxes = $(".checkbox");
var allChecked = $.grep(allCheckboxes, function(n,i){
return $(n).is(":checked");
}); //grep returns all elements in array that match criteria
var allUnchecked = $.grep(allCheckboxes, function(n,i){
return $(n)is(":checked");
},true); //invert=true returns all elements in array that do not match
// check the lengths of the arrays
if (allChecked.length == allCheckboxes.length)
$("#toggle").text("De-select All");
if (allUnchecked.length == allCheckboxes.length)
$("#toggle").text("Select All");
}):

jQuery click() on checkbox is not checking checkbox before running click handler

I was calling jQuery.click() on all my checkboxes when a global checkbox is checked. I want to disable a button if none of the normal checkboxes are checked. Hence, I was counting number of checked checkboxes using the code below. But when we manually click on .chkLst happens $(this) comes already checked and when I call click() function, $(this) comes unchecked.
$(".grid").on("click", ".chkLst", function() {
if($(this).is(":checked")){
deleteBtnDisableCheck++;
} else {
deleteBtnDisableCheck--;
}
if (deleteBtnDisableCheck == 0) {
$('#btnDeleteLst').addClass("btnDisable");
} else {
$('#btnDeleteLst').removeClass("btnDisable");
}
});
$(".grid").on("click", ".chkLstAll", function() {
$(".chkLst").each(function() {
$(this).click();
});
});
You can do the above operation easily using selector, so you dont require a counter variable.
//function to call when local checkbox is clicked
$(".grid").on("click", ".chkLst", function() {
callUpdateClassFunction();
});
//function to call when global checkbox is clicked
$(".grid").on("click", ".chkLstAll", function() {
$(".chkLst").prop('checked',this.checked);
callUpdateClassFunction();
});
//function to update class
function callUpdateClassFunction(){
if($(".chkLst:checked").length > 0){
$('#btnDeleteLst').addClass("btnDisable");
}
else{
$('#btnDeleteLst').removeClass("btnDisable");
}
}

Javascript iterate through all checkboxes on submit, and set attribute if changed from original value

I am trying to make a javascript function similar to the following, except it will iterate through all the checkboxes when the user clicks the submit button:
$('.checkboxstatus').click(function(){
this.setAttribute('checked',this.checked);
if (this.checked && $(this).data("def") == 0){
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else if(!this.checked && $(this).data("def") == 'checked')
{
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else{
//no change in checkbox
this.setAttribute('changed', 'no');
}
});
When the user clicks submit, the function should be called and it should iterate through all checkboxes and see if the checkbox is checked and see if the data-def is checked or 0. If the checkbox is checked and data-def="checked" then nothing should happen. If the checkbox state is different from the data-def then an attribute ("changed") should be added to that checkbox with value of "yes". Any suggestions on how to go about this?
Your question almost gives you the answer. You need to attach a "submit" event handler to the form, then grab all input[type=checkbox] and set the "changed" attribute accordingly.
I'm not sure I get this, but the usual way to do something like this would be to set an initial state in data, then on submit, prevent the submit action, check all the checkboxes against that initial state data variable, and see if anything changed, if it did, trigger the native submit handler ?
var boxes = $('input[type="checkbox"]').each(function() {
$(this).data('initial_state', this.checked);
});
$('form').on('submit', function(e){
e.preventDefault();
var same_same = true;
boxes.each(function() {
if ( $(this).data('initial_state') !== this.checked ) { // has changed ?
$(this).data('changed', true);
same_same = false;
}
});
if ( ! same_same ) { // diffelent
this.submit();
} else {
alert('same same, but not diffelent!');
}
});

Categories

Resources