JavaScript cannot check checkbox - javascript

This is my code: https://jsfiddle.net/56xh3rLo/
Here is the javascript from the jsfiddle:
$(document).ready(function() {
$(document).click(function(event) { //line 1
if(!$(event.target).closest('.menu').length) { //line 2
if ($('.menu-btn').is(':checked')) { //line 3
$('.menu-btn').trigger('click'); //line 4
}
}
})
})
as you can see, line 1 is to detect if a user is going to click on the page. line 2 is to detect if the user clicks on anywhere EXCEPT for the .menu element (which is anywhere in the black background). Line 3 is to detect if the .menu-btn checkbox is checked. if it is checked, it will trigger a click on the checkbox.
So, here is the summary of the code: if the user clicks on anywhere EXCEPT for the black box area and the checkbox IS checked, the code will trigger a click on the checkbox and it will uncheck the checkbox. the problem is, the checkbox does not even check at all. why is it not working?

You want to change your outer if check to
if(!$(event.target).closest('.menu').length && !$(event.target).hasClass('menu-btn')) {
The way you're doing it now is seeing if the click target has an ancestor with the .menu class, but if you click the checkbox, it will not have that ancestor. This means the outer if check will pass, then the inner if check will pass because the click you just did checked the box. That will run the line
$('.menu-btn').prop( "checked", false );
Here's the working example.

The proper way to uncheck a checkbox with jQuery:
$('.menu-btn').prop( "checked", false );

A bit expressive, but I hope it will be more clear to the reader:
$(document).ready(function() {
var $window = $(window);
var $btn = $('.menu-btn');
$window.on('click', function (event) {
var $target = $(event.target);
if($target.is($btn)) {
return;
}
if($btn.is(':checked') === false) {
return;
}
if ($target.closest('.menu').length > 0) {
return;
}
$btn.prop('checked', false);
});
});

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.

Can't change radio button selection

I have some tables (more than one), when I select one table by clicking on it, I need that the first radio button is selected.
It works fine, but if I want to change the option of the radio button i cant. It keeps always the first one marked.
Here is a fiddle with the issue:
https://jsfiddle.net/jzbm4j60/
$('table').click(function(event) {
$('table').removeClass('focus');
event.stopPropagation();
$(this).addClass('focus');
var $firstRadio = $(this).find('input:radio[name=rdGoFerrys]:first');
var $secondRadio = $(this).find('input:radio[name=rdBackFerrys]:first');
if ($firstRadio.is(':checked') === false) {
$firstRadio.prop('checked', true);
}
if ($secondRadio.is(':checked') === false) {
$secondRadio.prop('checked', true);
}
});
The click event on your inputs is bubbling up the DOM and triggering the click event you have on your table. Stop that behavior by using:
$('input').click(function(e) {
e.stopPropagation()
})

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();
}
}
);

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.

If one checkbox is checked, end function

I have a div with the id "PCsetup" set to slide open when any of three check-boxes (#PCOF, #PCTMI, or #PCRM) are checked, but if one or two of the three is already checked, and the user checks another check-box, I want to end the function before it slides open, as it would actually close the "PCsetup" div. How can I have the function check if the other two check-boxes are checked, and if they aren't, have the div slide down? Here's what I have so far:
$(function() {
$("input[type=checkbox]").on('click', function(){
if ($("#PCOF").is(':checked'))|| ($("#PCRM").is(':checked')) {
return;
} else if $('#PCTMI').is(':checked')){
$("#PCsetup").slideDown("slow");
} else {
$("#PCsetup").slideUp("slow");
}
});
A couple things: 1. The anonymous function in your example isn't closed, so the code isn't valid. 2. I had a hard time following exactly what you're trying to accomplish, but it sounds like you want to show the div if any combination of checkboxes are checked and hide it if none are checked. This will get you that result:
$(document).ready(function() {
$(function() {
$('#PCOF, #PCTMI, #PCRM').on('click', function() {
var numChecked = $('#PCOF:checked, #PCTMI:checked, #PCRM:checked').length;
if (!numChecked) {
$('#PCsetup:visible').slideUp('slow');
} else {
$('#PCsetup').slideDown('slow');
}
});
});
});
http://jsbin.com/IsutuhI/3
something like
$(function() {
var $chks = $('#PCOF, #PCRM, #PCTMI');
$chks.on('click', function(){
var checked = $chks.filter(':checked').length > 0, visible = $("#PCsetup").is(':visible');
console.log('dd', checked, visible)
if (checked && !visible) {
$("#PCsetup").finish().slideDown("slow");
} else if(!checked && visible){
$("#PCsetup").finish().slideUp("slow");
}
});
});
Demo: Fiddle

Categories

Resources