Input:Checked jQuery vs CSS? - javascript

Unless I am mistaken. jQuery and CSS handle the :checked selector very differently. In CSS when I use :checked, styles are applied appropriately as I click around, but in jQuery it only seems to recognize what was originally in the DOM on page-load. Am I missing something?
Here is my Fiddle
In jQuery:
$('input:checked').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
In CSS:
input:checked+label {font-weight:bold;color:#5EAF1E}
UPDATE:
I should clarify that what I am looking to do is trigger behavior if a user clicks an already selected radio button.

Try setting up the handler this way:
$('body').on('click', 'input:checked', function() {
// ...
});
The way you have it, you're finding all the elements that are checked when that code runs. The above uses event bubbling so that the test is made when each "click" happens.
Inside your handler, you're updating the style for all checked elements, even though any particular click will only change one. That's not a huge deal if the number of checkboxes isn't too big.
edit — some further thought, and a helpful followup question, makes me realize that inside an event handler for a radio button "click" event, the button will always be ":checked". The value of the "checked" property is updated by the browser before the event is dispatched. (That'll be reversed if the default action of the event is prevented.)
I think it'll be necessary to add a class or use .data() to keep track of a shadow for the "checked" property. When a button is clicked, you'd see if your own flag is set; if so, that means the button was set before being clicked. If not, you set the flag. You'll also want to clear the flag of all like-named radio buttons.

You bound the event only to the inputs that were initially checked. Remove :checked from the first selector and it works as intended (but ugly.)
http://jsfiddle.net/8rDXd/19/
$('input').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
you would of course need to "undo" the css change you made with jQuery to make it go away when the input is unchecked.
$('input').click(function () {
$('input').css('background','').filter(":checked").css('background','#FF0000');
$('input+label').css('background','');
$('input:checked+label').css('background','#ff0000');
});
http://jsfiddle.net/8rDXd/20/

AFTER UPDATE
Keep track of the status of the radio buttons. For example, use .data() to keep an in-memory state of the radio buttons.
$(function () {
var $radio = $(":radio");
$radio.filter(":checked").data("checked", true);
$radio.on("click", function () {
if ($(this).data("checked")) {
alert("Already selected");
}
$radio.data("checked", false).filter(":checked").data("checked", true);
});
});
See it live here.
BEFORE UPDATE
I think you want to use .change() here.
$('input:radio').change(function () {
$('input, input+label').css('background', '');
$('input:checked, input:checked+label').css('background', '#f00');
}).change();
See it live here.

Related

Why does jquery not respond accordingly to my conditions?

I want my tablerows to have the class 'clickable' only if edit mode is turned on. With element inspect I can see that this works. It succesfully removes the 'clickable' class if I turn off edit mode.
If a table row has the class clickable it will click it's checkbox upon clicking the table row. This works too, however when I turn off edit mode, I'm still able to click tablerows and by doing so, also check the checkbox.
If you can see something that I've overlooked please let me know.
function clickableTableRow(isClickable) {
if (isClickable) {
$(tableBody).find('tr').each(function () {
$(this).addClass("clickable");
$(this).click(function () {
$(this).find('input[type=checkbox]').click();
});
})
} else {
$(tableBody).find('tr').each(function () {
$(this).removeClass("checked").removeClass("clickable");
$(this).find('input[type=checkbox]').prop("checked", false);
})
}
}
So to clarify, in element inspect I can see that it does all as it should, so I think the problem lays in the function where I make a checkbox click upon clicking on a tablerow
Use .off()
$(this).off('click');
The off() Method in jQuery is used to remove event handlers attached
with the on() method -or the .click() method. The off() method brings a lot of consistency to
the API and it replace unbind(), die() and undelegate() methods.
The event handler was still active, using .off() turns it off. Adding this line of code tot the else statement solved the issue:
$(this).off('click');

Change Div Class on click takes multiple clicks before it works

I used the methods in this question:
change div class onclick on another div, and change back on body click
So here's my jQuery function:
jQuery('.checkbox_wrapper').on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
However it doesn't seem to be working properly. It takes multiple clicks before the class changes.
See my jsfiddle:
http://jsfiddle.net/7A3vw/
I cut it down to the bare essentials thinking it might be conflicting javascript, but even with the single function it takes multiple clicks before the class actually changes. Because the production environment has 1 click toggle a hidden checkbox, multiple clicks is not reasonable.
Could someone help me figure out what's causing this issue?
The click function fires twice, once for the image, and once for the input, as both will bubble to the parent element, and firing twice reverts the classes again (proof).
Just target the image instead, as that is what you're really trying to click, not the parent :
jQuery('.deck_card img').on('click', function (e) {
jQuery(this).closest('div').parent().toggleClass('not_selected selected')
});
FIDDLE
i guest you need the checkbox checked together with the toggling of your div.
$(document).ready(function(e) {
$('.checkbox_wrapper').on('click', function(e){
var checked = $(this).find('input[type="checkbox"]').is(":checked");
if(checked){
jQuery(this).parent().addClass('selected').removeClass('not_selected');
}else{
jQuery(this).parent().addClass('not_selected').removeClass('selected');
}
});
});
Your code is triggering click event twice. So use .preventDefault()
This makes the default action of the event will not be triggered.
$('.checkbox_wrapper').on('click', function(e){
$(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
e.preventDefault(); // prevent the default action to be
}); // triggered for next time
Check this JSFiddle
try this
jQuery(document).on("click",'.checkbox_wrapper', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
Multiple Clicks are getting triggered because you are using class selector. You need to use not to exclude extra elements :
jQuery("div.checkbox_wrapper :not('div.checkboxdiv')").on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected selected')
});
Here is a FIDDLE.

Listen for changes of checked/disabled in jQuery

I have some object (div, input/checkbox) in an HTML page. The values for their "checked" and "disabled" attributes are set via some JS functions. I want to listen to changes of these attributes, but couldn't find any function or listener to perform that.
How can I add an event listener that listen on changes of "checked" or "disabled" and execute some code (e.g. changing style of checkbox / div) depending on the attributes' status?
Thanks
Regarding the "disabled" change, you may be able to listen to DOMAttrModified events. See this test case for details:
http://jsfiddle.net/4kWbp/1/
Note that not all UAs support DOM mutation events like DOMAttrModified, and in those that do support them, listening to them may cause performance to detoriate.
Setting .checked directly does not trigger "change" events, and doesn't seem to trigger DOMAttrModified either (only tested in Opera though, and this is the sort of under-specified between-the-spec-gaps stuff that might well be very inconsistent across browsers. Perhaps it's an Opera bug.)
The last resort would perhaps be defining getters/setters for those properties. That would be a rather ugly hack though..
You can use the pseudo-selectors for :checked and :disabled and trigger an empty animation which causes an animationstart event. For example:
select > option:checked {
animation: checked 1ms;
}
select > option:not(:checked) {
animation: unchecked 1ms;
}
#keyframes checked { from {}; to {}; }
#keyframes unchecked { from {}; to {}; }
and then in javascript you can use:
document.body.querySelector('select').addEventListener('animationstart',
function (ev) {
console.dir(ev);
});
The event has available animationName and target properties which give you enough to work with.
$('#Checkboxid:checked') this will return true if checkbox value is on and false if checkbox value is off.
this is jquery selector function :checked can be use to check radio and checkbox values.
syntax is as follows:
$('#checkboxid:checked')
To 'listen' to when a checkbox has been toggled use change():
$('.target').change(function() {
console.log(this.checked ? 'Checked' : 'Not Checked');
});
Use the :checked to determine the checked radio or checkbox on the page or container.
First of all check this jsfiddle
after this follow this stackoverflow question Jquery get selected checkboxes to write for your desired result.
you can check disabled or not as:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
});
set=unset;
});
});
Check these links for detail:
Jquery get selected checkboxes
Setting "checked" for a checkbox with jQuery?
I don't have answer to your question, but I could suggest you to try something like Event Bus (in GWT is Event Handler).
For JQuery you can use Events.

Sequence of Events, alert is faster then removeAttr

i got following problem, i need to build a two checkboxes; where only one can be selected at a time, but onchange there will be a live calculation.
$('#calculator input, #calculator select').change(function() {
$('#calc_keller_true').click(function() {
$('#calc_keller_false').removeAttr('checked');
});
$('#calc_keller_false').click(function() {
$('#calc_keller_true').removeAttr('checked');
});
liveCalculate();
});
This is how it looks like, which is working but it seems to slow cause in my function liveCalculate i do this.
function liveCalculate() {
// Getting the value of the checked checkbox
var calc_keller = $('input[name=calc_keller]:checked').val();
alert(calc_keller);
}
So when i click on the false button the alert will trigger before my removeAttr and both Checkboxes will be 'checked' at the moment of the alert.
Anyone got a plan why exactly the liveCalculate function triggers faster then the removeAttr ?
Do i miss some basic knowledge in how the order works in javascript ?
Best Regards,
jay7
You only need to add click-handlers once. In your above example, you are adding them again and again, for every 'change' event you have on the select box.
Furthermore, you are not actually removing the attr on the change event, that happens during the click events. However, you fire liveCalculate after the change event.
Consider the following:
$('#calc_keller_true').click(function() {
$('#calc_keller_false').removeAttr('checked');
});
$('#calc_keller_false').click(function() {
$('#calc_keller_true').removeAttr('checked');
});
$('#calculator input, #calculator select').change(function() {
$('#calc_keller_false').removeAttr('checked');
$('#calc_keller_true').removeAttr('checked');
liveCalculate();
});
I'm not entirely sure if that accomplishes what you're expecting (simply because it isn't 100% clear to me what you do expect to happen).

jQuery Checkbox/Target _Blank

I have the following jQuery on my website:
$(function() {
$('#newtab').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
The code is for a checkbox that toggles the target of links on my page (when checked, links open in a new tab (target="_blank"), otherwise, they open in the same page.
I have two issues:
I want to make it so only links in a particular div are affected by the toggle (I essentially just don't want links in my menu to be affected by it).
When clicking the checkbox, the check is never shown for some reason. I have <input type="checkbox" id="newtab" /><label for="newtab">Open links in new tab</label>
on my page which shows the checkbox (unselected). When I click on it, it changes the target attribute, but the checkbox never appears to be selected; it still shows the empty box. Clicking the checkbox again removes the target attribute as expected.
Thanks.
This should solve your problem: http://jsfiddle.net/UJMgQ/2/
$(function () {
$('#newtab').click(function () {
if ($(this).is(':checked')) {
$('#wanted a').attr('target', '_blank');
} else {
$('#wanted a').removeAttr('target');
}
});
});
To limit the a's that are selected just change #wanted to what ever div(container) the a's you want are in. It works like a css selector.
For part 1: $('.divYouWant a').attr(...) will limit it, just like a CSS selector would.
For part 2: According to the docs of toggle() "The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.". If you don't want that, either use .click(), or just set $('#newtab').checked equal to one in the selected function, and 0 for the unselected function.
Try: $('#mydiv').find('a').attr('target', '_blank');
I think toggle wants you to return true to make the click event propagate to the checkbox. Not sure, but checking the docs may be in order here...
Nevermind, docs say that toggle prevents propagation. Perhaps use something like $.change() instead, and use the value of the checked property to set the values you want.

Categories

Resources