nktokyo
nktokyo

Reputation: 672

Trigger a Jquery after setting a checkbox (rails)

I have a checkbox which is generated from the following code:

<%= f.input :all_new_zealand, :as => :boolean, :label => "All of New Zealand", :wrapper_html => { :style => 'display: inline' } %> 

The HTML generated is:

<input name="investor[all_new_zealand]" type="hidden" value="0">
<input class="boolean optional" id="investor_all_new_zealand" name="investor[all_new_zealand]" type="checkbox" value="1">
<label class="boolean optional" for="investor_all_new_zealand">All of New Zealand</label>

I'm trying to show and hide a div based on the checking/unchecking of that field. According to the Jquery Missing Manual guide I'm reading the query to find out the status is

if ($('#id_name').attr('checked')) {
 ...
} else {
 ...
}

However this isn't working and in the html debug console I can't see the existence of a "checked" attribute.

I put in some debug statements and found that regardless of what the value was on the screen, jquery was seeing the value as when the screen was loaded, ie the below code would give the same result (that of what the checkbox was set to upon load) regardless if I was checking or un-checking the button.

$(function(){
    $('#investor_all_new_zealand').click(function() {
        alert($('#investor_all_new_zealand').val(); 
    });
});

Any hints at what I am missing here would be appreciated. I'm a relative beginner here.

Thanks!

Upvotes: 1

Views: 444

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Use JavaScript change event , for listening use jQuery change() method

$(function(){
    $('#investor_all_new_zealand').change(function() {
        alert(this.checked?"checked":"not checked"); 
    });
});

Fiddle Demo

Documentation

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

You need to listen to the change event, and to check whether the field is checked or not use the checked property of the dom element

$(function(){
    $('#investor_all_new_zealand').change(function() {
        alert(this.checked); 
        if(this.checked){
            alert('checked')
        } else {
            alert('ot')
        }
    });
});

Upvotes: 1

Related Questions