Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a drop-down list where you can select a person.

<%= select_tag "person", options_from_collection_for_select(Person.all, :id, :name, 1) %>

When a person is selected I want to display that persons phone number. How can I do that?

After looking at a lot of solutions of how to use Javascript/jQuery/CoffeeScript in RoR I´m a bit confused over what to place in which files and what to use. Can someone please give me a simple example?

share|improve this question

1 Answer

Pass your changed person id to javascript function on onchange event.


<%= select_tag "person", options_from_collection_for_select(Person.all, :id, :name, 1) ,
 :onchange => "your_js_function_to_display_phone_for(this.value)"%>

Trigger an Ajax request and return back the phone number from database. ( You can do this from client side too if the person list is small )


<script type="text/javascript">

function your_js_function_to_display_phone_for(person_id)
{

// Given a person_id 
// I am assuming this route will return me the Phone Number 

new Ajax.Request('/person/get_phone_number/'+person_id,
{asynchronous:true, evalScripts:true,
method:'post', 
onSuccess:function(request)
{
    // Modify this place to whether update on particular div_id 
    // or do appropriate action with returned request.body 

    alert("Phone Number for this Person is: "+request.body);
}, 
parameters:Form.serialize(this)});
}

</script>

EDIT:

Your controller should do something like this.

class PersonController
    def get_phone_number
        person = Person.find(params[:id])
        phone_number = person.get_phone_number 
        render :text => phone_number 
    end 
end 
share|improve this answer
Thank you for your answer, but I can't get it to work. Can you please explain how I should return the phone number? – ana Apr 19 at 13:34
Please view the edit – karthikselvakumar Apr 22 at 13:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.