1

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That .checked conditional doesn't seem to work in the
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.