views:

389

answers:

2

I want to add a simple onChange event to a select list I have in Rails. How do I do this?

This is the select box code:

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

The onChange event is supposed to call a function, fillAnswerNumber(), which takes the currently selected value and adds a bunch of options to another select list based on the result.

edit: I realised that i needed an onChange event actually...

+1  A: 

Using jquery, I would bind the event on the client (on document load).

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

Nothing you need to do inside Rails to get this working, other than either explicitly define an id (but Rails will provide one for you if using the form builders)

Toby Hede
A: 

I think I figured it out... thanks to some SO answers and a couple of handy blog posts.

Here's what I've got. My select looks like this:

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

and my JavaScript (JQuery) code looks like this:

: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"))
      ;
    }
  }
Ganesh Shankar