2010-02-23 34 views
1

我想將一個簡單的onChange事件添加到我在Rails中選擇的列表中。我該怎麼做呢?附加onChange事件以在Rails中選擇列表

這是選擇框的代碼:

= f.select(:question_type_id, QuestionType.all.collect {|qt| [ qt.name, qt.id ]}, { :include_blank => "Please Select a Question Type" }) 

onChange事件應該調用一個函數,基於fillAnswerNumber(),它當前所選的值,並增加了一堆選項到另一個選擇列表結果。

編輯:我意識到我需要一個onChange事件其實...

回答

2

我想我想通了...感謝一些SO的答案和一些方便的博客文章。

這是我得到的。我選擇這個樣子的:

= f.select(:question_type_id, QuestionType.all.collect {|qt| [ qt.name, qt.id ]}, { :include_blank => "Please Select a Question Type" }, :onchange => "fillAnswerNumber();") 

和我的JavaScript(JQuery的)代碼如下所示:

:javascript 
    function fillAnswerNumber(){ 
    var question_type_name = $("#question_question_type_id :selected").text() 
    if(question_type_name == "Single Input"){ 
     $("#answer_number") 
     .find('option') 
     .remove() 
     .end() 
     .append($('<option selected="selected"></option>').val("1").html("1")) 
     .append($('<option></option>').val("2").html("2")) 
     .append($('<option></option>').val("3").html("3")) 
     .append($('<option></option>').val("4").html("4")) 
     ; 
    }else if(question_type_name == "Multiple Choice"){ 
     $("#answer_number") 
     .find('option') 
     .remove() 
     .end() 
     .append($('<option></option>').val("3").html("3")) 
     .append($('<option selected="selected"></option>').val("4").html("4")) 
     .append($('<option></option>').val("5").html("5")) 
     .append($('<option></option>').val("6").html("6")) 
     ; 
    } 
    } 
5

使用jQuery,我會在客戶端上的事件(上載文件)進行綁定。

$("#select_id").onclick(function(){}); 

沒有需要裏面的Rails做的就是這個工作,除了明確地定義一個ID(但Rails會如果使用表單建設者提供了一個給你)

+2

其實,你想要的jQuery的觸發改變... $( 「#select_id」)變化(函數(){})。 – mindtonic 2010-12-16 16:40:32

1

我想,那麼你需要添加jQuery的生活,觀察選擇框的變化和發送Ajax請求獲取結果並將結果填充到另一個selectox中。

的僞代碼可能看起來像這樣

$('#question_type_id').live('change',function(){ 
$.ajax({ 
    url: url_to_fetch_result, 
    success: function(responseData) { 
     populate your next select depending your resposeData here 
    } 
}); 

現場使用的優點是選擇框改變事件被觸發,即使你動態加載$(「#question_type_id」)選擇框後的時間。

願這幫助

相關問題