简体   繁体   中英

Using Javascript in Ruby on Rails

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´ma bit confused over what to place in which files and what to use. Can someone please give me a simple example?

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 

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