简体   繁体   中英

Rails jquery only loaded to first element

I want to create a drop down with links to different controller actions. I have a helper method to provide options for my drop down.

   def my_product_options(product)
    if product.status == Product::STATUS_INCOMPLETE
       my_options =  {"Select" => '', "Edit info" => edit_product_path(product)}
    elsif product.status == Product::STATUS_ACTIVE
       my_options =  {"Select" => '', "Edit info" => edit_product_path(product), "Suspend" => suspend_product_path(product)}
    end
    my_options
   end

I loop through each product and get options for each product. but the problem is all products get their drop down loaded with their options but the click works only for the first product. when i click drop down option for the rest nothing happens.

I have jquery to handle the click event in the view

<script>
$('#create_options').change(function() {
    window.location = $(this).find('option:selected').val();
});
</script>

Any suggestions or solution or different approach would greatly help. Thanks.

Yes that happens when you use same ids for multiple elements on a same document. You have to use class instead.

$('.create_options').change(function() {
 //^-----use class instead of id
    window.location = $(this).find('option:selected').val();
});

See: http://jsfiddle.net/X5583/

In fiddle you can see both "using ids" and "using class" try commenting out each
one by one.

If you use same id notation for multiple elements in a same page then only first of the occurance will get the event not others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM