In a Rails 3 app using Jquery, I’m trying to dynamically show/ hide form elements, based on whether a boolean field is true or false.
At present my jquery function looks something like this:
$(function() {
$('#boolean').change(function(){
if ($(this).value == true) {
$('.hidden-fields').show();
} else {
$('.hidden-fields').hide();
}
});
})
How do I correctly pass the boolean fields value into this function such that:
- the function is initialized on page load, and fields hidden/shown
based on the value in the database; and - the fields are toggled when the boolean is changed.
Sorry of this is a simple question. I’m trying to get to grips with javascript and really appreciate any pointers.
Thanks
Do you only have one element on your HTML page with an id of boolean? Because using
#booleanwill return the first one only. If you have many, you should use a class ofbooleaninstead, and then use.booleanto reference all elements with that class.But to your questions:
1) Your example code there will be run on page load and will automatically apply to all elements with a .boolean class (assuming you go that way). If you want to immediately hide or show elements because, say, a value in the DB is set to
false, then you should do that when you’re rendering your page in your ERB or HAML or whatever view.2) If the element you’re attaching this JS to is a select box or something that will have a change() function, then you’re all set to go. If you’re wondering if, when the DB changes, this view automatically changes its visibility, then that is something different.