Checkbox not working before using script - javascript

I was asked to mark as checked the checkbox on the table line click, the script below is working but now when I click directly on the checkbox, it doesn't work, works only if I click the table line.
I have this html:
<tr class="linha_tela" id="4">
<td>Profile</td>
<td>Clientes</td>
<td>
<input type="checkbox" checked="checked" id="controller_4" name="controllers[]" value="4" />
</td>
</tr>
And this is my script:
$('.linha_tela').click(function(){
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
});
Thanks

What's happening is that the checkbox is toggling when you click on it, then the event handler is triggered causing it to become unchecked. This is basically occurring instantaneously, which is why it appears to just not work at all.
Try this:
$('.linha_tela').click(function(event) {
if (!$(event.target).is(':checkbox')) {
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
}
});
Edit: Here's a jsfiddle demo of it working.

This is happening because the checkbox is in the table row, so when you are clicking it, it's changing it's status (because that's what checkboxes do).
Then the click is bubbling up to your tr, and running the script, which is changing it status back.
you need to check the event target, and if it's not an input, do your thing, if it is, then don't.
here's the modified script:
$('.linha_tela').click(function(event) {
if (event.target.nodeName != 'INPUT') {
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
}
});
and a link to a jsfiddle to try it out:
http://jsfiddle.net/yDEyC/

$(":checkbox").click(function(event) {
event.stopPropagation();
});
This should work.

Here is a jsfiddle that demonstrates your code scenario:
http://jsfiddle.net/sAfTT/
The problem you're running into is a common one with events in HTML. When events are fired, they are fired on every element to which they can be applied in order from closest to furthest away. This is called bubbling(theres also capturing which works in reverse). http://www.quirksmode.org/js/events_order.html
So, in reality, when you are clicking on the checkbox, you are also clicking on the row, so the handler call looks like this.(assuming the box is unchecked to start with. reverse check/uncheck as applicable)
Checkbox clicked: check the box
Can I bubble up? Yes
Row clicked. Is there an event handler? Yes
Fire event handler (yours). This determines if the checkbox is checked. It is.
Because the box is checked, uncheck it.
Can I bubble up? Yes
Table Clicked. Is there an event handler? no
Document Clicked. Is there an event handler? No.
you can attach an event handler to the checkbox directly to prevent bubbling
$(':checkbox').click(function(e){
e.preventDefault();
e.stopPropagation();
})​
edit: I could never get the prevent default to work just right in jsfiddle, but the concept provided by the other answers work nicely too.

Related

Canceling checkbox's click event prevents checking it?

I need to have a list of checkboxes with the condition that at least one of them must be checked.
The following code produces that effect.
document.querySelector('div').addEventListener('click', function(evt){
if( this.querySelectorAll('input:checked').length == 0 )
evt.preventDefault() ;
}) ;
<div>
<input type=checkbox checked>
<input type=checkbox>
<input type=checkbox>
</div>
That's fine, however, I don't understand why this code even works.
Firstly, I'm doing a .preventDefault() on the click event only after I've checked the condition that says there are no checkboxes checked. So canceling the click event at this point should make no difference.
Secondly, the code works even if you try to check the checkboxes using the keyboard, which is totally weird because I'm only canceling the click event.
Please explain why the code works the way it does.
While an input event listener is running, its effect on the element's state is actually already performed. If event.preventDefault() is called, this change is undone when the listener returns. This allows a checkbox event handler to test the new state of the checkbox, and allows the handler for a keyboard event on a text input to test the value that includes the new input.
The reason it works when you use the keyboard is that the click event is a high-level event that encompasses all the different ways to click on a checkbox: you can do it with the mouse, with they keyboard, with a touchscreen, etc. If you want to listen to a specific mode of clicking, you would have to use mousedown, keypress, etc.

Simple Modal Popup not displaying after searching JQGrid Results

Below is my
fiddle
HTML:
<table id="grid"></table>
I have an edit button and delete button in my JqGrid.
What my problem is, whenever a search happened in jQGrid, after clearing the values in searchbox, i am not getting any action when i am clicking on edit button and delete button.
Can someone suggest me what is the issue here?
Thanks,
You need event delegation here as buttons are generated dynamically,
$('#grid').on('click','.editbtn',function(){
alert('edit clicked here');
});
$('#grid').on('click','.delbtn',function(){
alert('delete clicked here');
});
Fiddle Demo
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

How to select check box without selecting the whole row (see body)?

Say, I have an html:
<div class="row">
<input type="checkbox">
</div>
When user clicks on the whole row, it becomes highlighted (selected class added by an onClick event). I attach onClick event to elements with class .row.
When user clicks on checkbox (which is inside .row), this checkbox becomes selected. But row should not be highlighted.
Is it possible to exclude the area of the checkbox from the area of the .row for an onClick event?
UPDATE
Here is what I have now: http://jsfiddle.net/saAGU/
I don't want class to be toggled when I click exactly on checkbox.
UPDATE 2
Here is the working solution with jQuery for future use: http://jsfiddle.net/saAGU/2/
Yes, it's possible. The right way to do it is putting a onclick event on the checkbox, capture the event and stop its propagation.
Something like this:
function checkboxClick (e) {
e.stopPropagation();
}
Please tell me if it worked
add click event to every checkbox and stop its propogation .this should work -
e.stopPropagation in event handler for checkbox click
http://jsfiddle.net/saAGU/3/
If you capture the event, and look at the event.toElement, you can see if they clicked on the .row or something else.
http://jsfiddle.net/saAGU/1/
$('.row').click(function(event){
if (event.toElement !== this) // Did the user click on the row directly?
return;
$(this).toggleClass('selected');
});

Why can't this checkbox, created dynamically with jQuery, be clicked?

jsFiddle
I'm using a jQuery plugin that allows the user to draw boxes in an area. I use jQuery to put a checkbox (along with a dropdown list) in the box that appears when the user lets go of the mouse button (this is towards the bottom of the javascript in the jsFiddle). The problem is, the checkbox is unclickable.
I do have some click checking code in the _mouseStart, _mouseDrag and _mouseStop events to stop another box from being created when you click in an existing box, but I don't think this is causing the problem because the dropdown list that is created can be clicked, and furthermore if you remove the click checking code the checkbox remains unclickable.
What is causing the checkbox to be unclickable? Thanks for reading.
EDIT:
Thanks to VinayC's answer, I can now see that the click reaches the checkbox, with this code:
$('#box').click(function(e){
alert('clicked');
$(this).attr('checked', true);
});
But the $(this).attr('checked', true); line doesn't make the checkbox checked. Can anyone tell me why? I've updated the jsFiddle
EDIT 2:
Harmen noticed that the code assigns the same id to each checkbox. In the actual code there's a counter appended to the id, so each one is unique, but I've taken that out because I think this is just a jQuery issue. I'd change the jsFiddle, but if you just create one box (thus one checkbox), the same problem occurs.
I've got no idea why, but while fiddling around (yes, on fiddlejs), this seems to do the trick
$('#box', ui.box).click(
function(evt){
evt.stopPropagation();
}
);
when setting up the box. See: http://jsfiddle.net/BBh3r/9/
I was actually trying to intercept the event and manually set it checked, but if there's no need to set it then hey.. Perhaps there's an extra event generated somewhere negating the first..? Click's only triggered once though.
Might be related to building jquery checkbox - can't set checked value
PS. Only tested on Chrome for Linux
You're creating multiple checkboxes with the same id.
It appears that top level event handlers are cancelling the click event. Add onclick event handler on check-box element alerting and you will see that click reaches to the checkbox.
Actually it is checked while the alert is visible, but it becomes unchecked afterwards. I'm guessing that after your event handler sets it to checked, the default event for the click (which is to toggle the check mark) happens, and since it is checked at the moment, it becomes unchecked again. Try calling preventDefault from the click handler.
You can also try this for a more universal approach
This worked for me.
$(document).click(function (e) {
if (element.tagName == 'INPUT') {
if ($(element).attr("type") == 'checkbox') {
e.stopPropagation();
e.preventBubble();
return;
}
}
});

Question regarding jQuery click() function

$('document').ready(function(){
$('[name=mycheckbox]').live('click', function(){
if($(this).is(':checked'))
{
alert('it is checked');
}
else
{
alert('it is not checked');
}
});
$('[name=mycheckbox]').click();
});
If the checkbox is checked and you click it, the alert box says, "it is not checked", but when the page runs and the click event is fired (with the checkbox checked), the alert box says, "it is checked". Why? Is the state of the checkbox not effected by the click event? Is it mousedown that changes the state?
Instead of click you should use the change event here, like this:
$('[name=mycheckbox]').live('change', function(){
And invoke it with the same trigger, like this:
$('[name=mycheckbox]').change();
The click is separate from the change, if you want the event to fire when the check actually has finished changing, then you want change, not click. Alternately, if you want to toggle it from it's initial state still, do this:
$('[name=mycheckbox]').click().change();
Instead of the live event (which I've found to be buggy at best) try binding a normal click even instead. I've done something similar which works fine with a .click event not .live("click",
I hope that helps :S
What is happening is quite subtle.
I have a button and checkbox linked to the following code:
$("#chkbx").click(function() {
if ($(this).is(':checked')) {
alert('checked');
}
else {
alert('unchecked');
}
});
$("#MyButton").click(function() {
$("#chkbx").click();
});
When I click on the checkbox, everything is displayed as you would expect.
When I click on the button, the reverse is true.
What is happening, is that when you click on the checkbox, it is firing the default click event before executing your code, and thus you code is taking the status from the aftermath of the default click event.
When you call the click method directly on the element, it is actually calling your click function and then executing the default event.
I'm not why this should be. or if this is intentional, or a bug.

Categories