David Hemmat
David Hemmat

Reputation: 156

Select onchange not calling function in rails 3

I am trying to use a select box to display a number of items. My select tag contains is written like this:

<%= select_tag "number_of_pets", options_for_select(allowed_pets_options, @pet_number_storage), onchange:"show_pet_forms(this.value, #{RecordsHelper::ALLOWED_PETS})" %>

and parses into HTML like this:

<select id="number_of_pets" name="number_of_pets" onchange="show_pet_forms(this.value, 4)">
    <option value="1" selected="selected">1 Pet</option>
    <option value="2">2 Pets</option>
    <option value="3">3 Pets</option>
    <option value="4">4 Pets</option>
</select>

In my application.html.erb file, in the head area, I have this javascript:

<script type="text/javascript">
function show_pet_forms(pets_selected, pets_allowed) {

    for (var i=1;i<=pets_selected;i++)
    { 
        element_id = "pet-" + i;
        document.getElementById(element_id).style.visibility = "visible";
        document.getElementById(element_id).style.display = "block";
    }
    for (var i=(pets_selected+1);i<=pets_allowed;i++)
    {
        element_id = "pet-" + i;
        document.getElementById(element_id).style.visibility = "hidden";
        document.getElementById(element_id).style.display = "none";
    }
}    
</script>

(Originally the javascript was in the coffeescript file, but I moved it while I was trying to figure out what the problem was.

The elements that I am trying to show and hide are these:

<div id="pet-1">
    SOME STUFF HERE
</div>
...
<div id="pet-4">
    SOME STUFF HERE
</div>

Unfortunately, I dont see any changes when I select one of the options in my select box, and I can't figure out if it is not triggering the event correctly, or if there is something wrong with my javascript (most likely). Where could the error be?

Thanks!

Upvotes: 0

Views: 895

Answers (1)

anpsmn
anpsmn

Reputation: 7257

The second for is not hiding the other divs.

for (var i=(pets_selected+1);i<=pets_allowed;i++)

In the above condition you are trying to add pets_selected + 1 which will concatenate than add.

You need to parse it into an integer first, then add.

for (var i=(parseInt(pets_selected)+1);i<=pets_allowed;i++)

See fiddle

Upvotes: 1

Related Questions