I'm just starting to try and use abit of jQuery in my app to change some css depending on if a checkbox is checked or not, I'm starting with this bit of code in my view:
<script type="text/javascript">
$(document).ready(function() {
if($("#area-1").is(':checked')) {
alert('checked!');
} else {
al开发者_StackOverflowert('not checked!');
}
});
</script>
And this is what is displayed for my checkboxes in the source:
<div class="filter_options_container">
<form class="form">
<fieldset class="filter_form_fieldset areas">
<input id="area-1" name="areas[]" type="checkbox" value="1" />
<label for="area-1"><p1>Area1</p1></label>
<input id="area-2" name="areas[]" type="checkbox" value="2" />
<label for="area-2"><p1>Area2</p1></label>
</fieldset>
<div class="form_filter_button">
<p2><input type="submit" value="Filter"/></p2>
</div>
</form>
</div>
edit
Rails view code for the form:<div class="filter_options_container">
<form class="form">
<fieldset class="filter_form_fieldset areas">
<% Area.all.each do |a| %>
<%= check_box_tag 'areas[]', a.id, false, :id => "area-#{a.id}" %>
<label for="area-<%= a.id %>"><p1><%= a.name %></p1></label>
<% end %>
</fieldset>
<div class="form_filter_button">
<p2><input type="submit" value="Filter"/></p2>
</div>
</form>
</div>
I was expecting it to give an alert message saying 'checked' when checking the area1 box and submitting the form but it only returns 'not checked' why is this?
Thanks for any help!
It looks like you're missing an event handler bound to the change/click*
event of the area-1
element. The code as you have it will only call the alert when the DOM has loaded and not when the value has changed. I think you want something like
<script type="text/javascript">
$(document).ready(function() {
$("#area-1").click(function() {
alert(this.checked? 'checked!' : 'not checked!');
});
});
</script>
Example code for you to have a play with
*the change event does not fire at the same point in time across browsers so the click event is recommended instead. However, jQuery fixes this problem across browsers.
If you want something to happen when the checkbox is clicked you will need to register an event handler to the checkbox.
$(document).ready(function() {
$("#area-1").click(function(){
if($(this).is(':checked')) {
alert('checked!');
} else {
alert('not checked!');
}
});
});
If you want the logic to fire on form submit you can register a function on $("form").submit();
$("form").submit(function() {
if ($("#area-1").is(':checked')) {
alert('checked!');
} else {
alert('not checked!');
}
});
Example of this on jsfiddle.
You can try this:
<script type="text/javascript">
$(document).ready(function() {
if($("#area-1:checked").length > 0) {
alert('checked!');
} else {
alert('not checked!');
}
});
</script>
It seems you are calling function when the document is ready. Initially check bos is not checked so it always return "not checked!". If you want to do this you may want to listen to submit button the evaluate the checked status.
精彩评论