Triggering a jquery action when the users mark a Checkbox - javascript

im very new in javascript and jquery. I have this checkbox:
<label for="editable">Editable </label><input name="editable" type="checkbox" id="edita"/>
And this jquery action:
$('#slickbox1').toggle(400);
return false;
I want to execute that action when the checkbox is checked. Thanks!

You could try:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
$('#slickbox1').toggle(400);
}
});
Although it's worth noting that running the toggle() method only when it's checked (assuming that it starts off un-checked) involves the user clicking the input once to show it, and then again to remove the check and again to re-check it so that it hides as a result of the toggle().
It might be worth considering:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
// checked
$('#slickbox1').show(400);
}
else {
// un-checked
$('#slickbox1').hide(400);
}
});
Which shows $('#slickbox1') if the check-box is checked, and hides it if not,
Or:
$('#edita').change(
function() {
$('#slickbox1').toggle(400);
});
Which toggles the $('#slickbox1') between show() and hide() when the input is checked and un-checked.
Edited to address the question raised by DomingoSL (the OP) in comments:
...can you please make an edit to see the procedure if now the triger is not a checkbox but a button?
There are two changes that need to be made to accommodate this:
a button has no change event, so it would have to use click() instead, and
a button has no :checked (or equivalent) state, so the if/else becomes redundant.
One way of doing it, though, and I'm assuming your element names remain the same since you've posted no information to the contrary, is:
$('#edita').click(
function(){
$('#slickbox1').toggle(400);
});

Related

Why does a checkbox always return the same value?

Edit3: Before more people keep downvoting this, please note this is not a duplicate question.
I'm working on a site that needs a table full of checkboxes and each one needs to be toggled on/off. Sometimes toggling one on needs to toggle others off and so on.
I did not build the base code, but since it was rather messy with all the logic going on, I decided to make some work like radios so we only have one base function to make much of the logic work.
I also have a function to enable/disable some checkboxes. It all works nicely, no problems at all.
But now there's another thing in play which is a text input. If a certain value is selected in it, some checkboxes automatically get turned on/off and locked in. The same base function is used to do this. But when a checkbox gets disabled with this, and then re-enabled, the following function keeps returning always true only for that checkbox:
$('input[type="checkbox"]').change(function() {
// Make checkboxes with names work like radios (radios can't be toggled off)
if ($(this).attr("name")) {
// Save clicked toggle value
var selected_toggle = $(this).attr('value');
// disable all and then toggle clicked one on
if ($('input[value="'+selected_toggle+'"]').prop("checked")) {
console.log("This is checked");
$('input:checkbox[name='+$(this).attr('name')+']').each(function() {
toggle_checkbox($(this).attr('value'), 'disabled');
});
toggle_checkbox(selected_toggle, 'enabled', 'on');
}
// Enable them all back if unchecking
else {
console.log("This is unchecked");
$('input:checkbox[name='+$(this).attr('name')+']').each(function() {
toggle_checkbox($(this).attr('value'), 'enabled');
});
$(this).parent().toggleClass("on");
}
}
else {
// Toggle them on or off
$(this).parent().toggleClass("on");
}
});
The obvious thing would be to say "something is different when locking/unlocking that checkbox", but it's all the same function and same way all other toggles get disabled, this is used from toggle_checkbox function:
function toggle_checkbox(toggle, value, on, lock) {
// Disable the toggle completely
if (value == 'disabled') {
$('input[value="'+toggle+'"]').attr('disabled', 'disabled');
$('input[value="'+toggle+'"]').parents('li').addClass('disabled');
$('input[value="'+toggle+'"]').parent().removeClass('on');
$('input[value="'+toggle+'"]').prop('checked', false);
}
// Enable a toggle back
if (value == 'enabled') {
$('input[value="'+toggle+'"]').parents('li').removeClass('disabled');
// Turn it on
if (on == 'on') {
$('input[value="'+toggle+'"]').parent().addClass('on');
$('input[value="'+toggle+'"]').prop('checked', true);
}
// Lock it on or remove disabled
if (lock == 'lock') {
$('input[value="'+toggle+'"]').attr('disabled', 'disabled');
}
else {
$('input[value="'+toggle+'"]').removeAttr('disabled');
}
}
}
When I remove the above code for name attributes, the checkbox works fine. Yet though every other checkbox returns Checked/unchecked properly, when clicking that specific un-disabled one, it always returns "this is checked".
I was using is(":checked") before, changing to prop made no difference.
Edit: As said in the comments, using prop or attr didn't make a difference. This is the code that is locking the checkbox that gets "stuck":
function set_hint_toggles(type, state) {
if (type == 'apples') { // Set when you select something with apples
toggle_checkbox('pears', 'disabled');
toggle_checkbox('apples', 'enabled', 'on', 'lock');
toggle_checkbox('oranges', 'disabled');
}
if (state == 'off') { // This is set when a reset button is pressed
var toggles_type = $('#hidden-input-with-value').val();
toggle_checkbox(toggles_type, 'enabled'); // This checkbox gets stuck, all others continue working
$('#text-input').removeAttr("disabled"); // Allows to type something again
}
}
Edit2: After trying Marvin answer I got a slighly different result that could help finding what's wrong:
This stuck checkbox has a "checked" and "disabled" state. When the reset button is clicked, disabled gets removed, but it remains checked (or should). When I tried to click the checkbox with the above code after reset, it was like it got re-checked once, and then kept stuck with checked.
Using [0].disabled = false, I can then keep toggling the checkbox on and off, but no js gets activated for it, and every click still returns checked.
Edit4: When attempting to use
toggle_checkbox(toggles_type, 'disabled');
toggle_checkbox(toggles_type, 'enabled');
In the code that makes the checkbox get stuck (set_hint_toggles(off) function above), it gets disabled only. Afterwards, this checkbox keeps returning always false instead of always true.
Theres a litle tip that you can use to improve your code.. Without a jsfiddle or some example, i'm afraid that i can't help you more than this. You should try using the DOM native api to set the disabled item
$('input[value="'+toggle+'"]')[0].disabled //returns if the element is disabled
$('input[value="'+toggle+'"]')[0].disabled = true //set element as disabled or not
The same works for the checked attribute.
$('input[value="'+toggle+'"]')[0].checked //returns if the element is checked
$('input[value="'+toggle+'"]')[0].checked = true //set element as checked or not
It truly was something wrong in the first block of code I posted. I'm now using this based off Adeneo's suggestion on changing the selectors and it's working perfectly:
// Search checkbox toggles
$('input[type="checkbox"]').change(function() {
// Make checkboxes with names work like radios (radios can't be toggled off)
if ($(this).attr("name")) {
if (this.checked) {
$('[name='+ this.name +']').each(function() {
toggle_disabled( this.value, 'disabled');
});
toggle_disabled( this.value, 'enabled', 'on');
}
else {
$('[name='+ this.name +']').each(function() {
toggle_disabled( this.value, 'enabled');
});
$(this).parent().toggleClass("on");
}
}
// Else if no name, just toggle on class
else {
$(this).parent().toggleClass("on");
}
});
I believe the problem was in the selector used for testing if the checkbox was on.
I'm also using prop on everything else now, but this did not change anything and does not seem like it had to do with the problem at all. The other suggestions also did not do anything.

Check if any checkbox in form is checked (MooTools)

I'm using a form with various checkbox groups and I would like the next button at the bottom of the page to appear only if any of the checkboxes is checked.
I found a working solution using jQuery here:
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});
http://jsfiddle.net/BPhZe/1937/
I'm looking for a way to do this with MooTools and I would prefer a solution where the button state is not "disabled" but hidden via CSS.
MooTools has the property Element.checked to see whether the specified element is set to "checked" or not. MooTools also allows you to add ":checked" to your selector to get only the selected elements that match. This means you can do something like this to determine whether any checkboxes are checked:
if ($$("input[type=checkbox]:checked").length > 0)
Or this to determine that no checkboxes are currently checked:
if ($$("input[type=checkbox]:checked").length < 1)
Given the sample form you linked to, here is one way to do it:
$$("input[type=checkbox]").each(function(checkboxInput) {
checkboxInput.addEvent("click", function() {
// show submit button if at least 1 checkbox is checked
if (checkboxInput.checked) {
$$("input[type=submit]").each(function(submitButton) {
submitButton.removeProperty("disabled");
});
}
// hide submit button if no checkboxes are checked
if ($$("input[type=checkbox]:checked").length < 1) {
$$("input[type=submit]").each(function(submitButton) {
submitButton.set("disabled", "disabled");
});
}
});
});
If your submit button had an id attribute – say, id="formSubmitButton" – you could reference it that way and accomplish the same thing using slightly less code, instead of having to use $$("input[type=submit]").each(function(submitButton) { ... } :
$("formSubmitButton").removeProperty("disabled");
To change from disabling / re-enabling the button to showing / hiding the button, you could initiate the form with the button set with property style="display:none;", and then call submitButton.removeProperty("style") when checkboxes are checked, and submitButton.setStyle("display", "none") when there are no longer any checked. Full code example for that version, using submit button with an ID:
$$("input[type=checkbox]").each(function(checkboxInput) {
checkboxInput.addEvent("click", function() {
// show submit button if at least 1 checkbox is checked
if (checkboxInput.checked) {
$("formSubmitButton").removeProperty("style");
}
// hide submit button if no checkboxes are checked
if ($$("input[type=checkbox]:checked").length < 1) {
$("formSubmitButton").setStyle("display", "none");
}
});
});

after using preventDefault, why can't i check a box with jquery?

How come the following code does not work. I prevent the default action on the event. Then I want to check the box anyway.
html
<input type="checkbox" class="checkbox" />
javsacript
$('.checkbox').click( function(e) {
e.preventDefault();
// some logic happens... now i may decide to check the box (in this case we want to check it for testing)
$('.checkbox').prop('checked',true);
});
You would think clicking the checkbox would still check the box.. but it doesnt. Check the fiddle to see what I mean.
http://jsfiddle.net/5KDH8/
I have also tried using the attr function without any luck.
You have to put the code that sets the "checked" property in a separate event loop:
setTimeout(function() { $('.checkbox').prop('checked', true); }, 1);
Either the browser or the library has to un-set the checkbox after the event handler returns, because it sets it in response to the click before the handler is invoked.
$('.checkbox').click( function(e) {
// do some logic that returns true or false
if (!mylogic) {
return false;
// returning false will prevent the checkbox to be checked.
}
});

Function on ANY checkbox change on the page

I'm new to JQuery in general and I want to have a function activate when ANY checkbox on the page is checked or not. Then it should check what state the checkbox is "checked" or not.
I'm not sure how to do this as all the examples I'd seen require the name of the checkbox in order to work. I'd be fine if this was in Javascript aswell.
Anyone have any ideas?
$('input[type="checkbox"]') would select all checkboxes on your page.
The following would run a function when any of your checkboxes are changed, and when checked:
$('input[type="checkbox"]').change(function(){
if($(this).is(':checked')) {//do something}
})
Bind dynamically your checkboxes to change event, and check if they are checked, then do a function of your choice.
$(document).on("change", ".chkelement", function(){
if( $(this).is(":checked") )
{
//DO SOMETHING
}
});
I recommend use a container other than "document", as close as possible to where checkboxes will be, but you get the idea right?

Checking the checked status of a checkbox upon its click

I am trying to test the status of a checkbox upon its click.
My problem is that it always reports as true as it reports the status after the change event has taken place and not before.
Is there anyway I can test before the change.
Current code using jQuery - the checkboxes all of class 'package':
$(".package").click(function(){
if($(this).is(":checked")){
alert($(this).attr("checked"));
}
});
This always returns true even if selecting a checkbox that is not currently checked.
EDIT : Ok seems there was some old js interfering with the process, after cleaning that up the click function did indeed work. Thanks all.
Using the onchange event on a checkbox is not cross-browser (hello IE! And yes, even with jQuery).
The following works:
$('.package').click(function() {
console.log(this.checked) // There is no need for jQuery here
})
Logs 'true' when you check the checkbox, and 'false' when you uncheck it.
And seriously, using $(this).attr('checked') or $(this).is(':checked') is just jQueryception for nothing.
You can use the change event instead, this way you are sure the previous checked state is always the oposite of what you read now
$(".package").change(function() {
alert($(this).attr("checked"));
});
The click event fires before the actual textbox change takes place, you need to subscribe to the change event:
$(".package").change(function(){
if($(this).is(":checked")){
alert($(this).attr("checked"));
}
});
Edit: Try querying the actual Javascript object itself, should work
$(".package").change(function(){
if(this.checked){
alert(this.checked);
}
});

Categories

Resources