简体   繁体   中英

Rails + AJAX: How do I change the text in a text_field input to the value of @shipping_address.name?

I have everything set up, where a click of a checkbox will fire a javascript function that makes an ajax call to a route that maps to a controller#action. The issue is that it's not escaping the embedded ruby.

This is my input tag:

<input id="address_name" type="text" value="sfsfsd" size="30" name="address[name]">

And this is the JS that fires off in my clone_shipping_address.js file:

$("#address_name").val("<%= @shipping_address.name =>");

Lets say my @shipping_address.name = "Edmund". The issue is that when I click the checkbox, the text that shows in the the text field becomes <%= @shipping_address.name => (literally), instead of Edmund . Does anyone know what I'm doing wrong?

The problem: Your file extension is '.js', which means this file is supposed to use only Javascript.

A solution: You can use Ruby code with ERB / HAML. Depending on which one you use, rename your file clone_shipping_address.js with the corresponding extension in order to execute the ruby code inside this file:

clone_shipping_address.js
# should become
clone_shipping_address.js.erb
# or if using HAML
clone_shipping_address.js.haml

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