2011-01-24 5 views
2

레일스 3 프로젝트의 양식 페이지에서 자바 스크립트 함수를 호출하려고합니다. 함수에 특정 요소의 ID를 보내야합니다. 불행히도 플러그인으로 자동 생성되므로 ID를 쉽게 얻을 수 없습니다.양식 요소의 자동 생성 ID를 자바 스크립트 함수로 보내려면 어떻게해야합니까?

것은 나는 이런 식으로 일을 시도 :

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

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

을 ..하지만 요소의 ID를 알고하지 않기 때문에, 나는 함수에서 호출 할 수 없습니다.

<% if (!the_value.nil?) && (!the_value.number_type.nil?) && ([email protected]_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 %> 

하지만 난 그 온로드는이 상황에 대해 작동하지 않습니다 실현 :

그래서 지금은 입력 요소로드 할 때 "온로드"에서 함수를 호출하여, 이런 식으로 할 노력하고있어. 이 문제를 해결할 수있는 방법이 있습니까? 내가 어떻게 하나

A) 첫 번째 옵션의 기능 분야에서 요소의 ID를 얻을, 또는

B)가이로드 할 때마다이 입력 요소에서이 함수를 호출?

... 또는 C) 다른 방법이 있나요?

미리 감사드립니다. 자세한 내용이 도움이 될 경우 알려 주시기 바랍니다.

+0

시도 컨텍스트를 사용하여 문제의 요소를 가져오고 가능하면 CSS className을 사용하여 요소 선택기에서 범위를 좁 힙니다. – Silkster

답변

1

당신이 모델에 저장된 ID가있는 경우,이 규칙에 <% = model.id의 %>

예외와 함께 당신은 객체를 생성하고 데이터베이스에 기록되기 전에 때입니다 얻을. 편집하거나 다른 곳으로 가면 괜찮을 것입니다.

페이지의 어딘가에 있다면 :/jQuery를 사용하여 얻을 수 있습니다.

< DIV 자료 = "id_of_the_element"attr_with_my_id = "15"> ABC </div>

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

< 입력 ID = "id_of_the_element ...> </입력>

$("#id_of_the_element").value 
+0

#id_of_the_element는 페이지가로드 될 때 생성되므로 불행히도 제가 모릅니다. 플러그인은 ajax로 양식 요소를 생성하며 각각은 고유하게 생성 된 ID를가집니다. "다른 필드 추가") – Sarah

+0

페이지와 함께 자바 스크립트 코드도 생성 할 수 있습니다. 그러면 이드를 알 수 있습니다. – m4risU

관련 문제