简体   繁体   中英

How can I send an automatically generated ID for a form element to a javascript function?

I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.

I tried doing it this way:

<%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>

<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !@id_types_sm.include? the_value.number_type) %>
    <script type="text/javascript">
        setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
    </script>
<% end %>

.. But since I don't know the ID of the element, I can't call it from the function.

So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:

<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!@id_types_sm.include? the_value.number_type) %>
    <%# Call the function from the form helper only if the conditions are met %>
    <%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>                  
<% else %>
    <%# Use the form helper without calling the function %>
    <%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(this.id);"} %>                     
<% end %>

BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either

A) get the element ID from the field to the function in the first option, or

B) call this function from this input element whenever it loads?

... or C) an alternative way to do this?

Thanks in advance and let me know if more details would help.

If you have ID saved in the model, get it with <%= model.id %>

Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.

If you have it somewhere on the page :/ then you can use jQuery to get it for you.

< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >

$("#id_of_the_element").attr('attr_with_my_id')

< input id="id_of_the_element ... >< /input >

$("#id_of_the_element").value 

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