[英]Javascript not picking up attribute value
Thanks to help here, I got a sample piece of code working When I tried to apply it to the real thing, something is not working quite. 感谢这里的帮助,我得到了一段代码示例。当我尝试将它应用到真实的东西时,有些东西不能正常工作。
In my view (new.html.erb), I have the following: 在我看来(new.html.erb),我有以下内容:
<%= f.hidden_field :addtl_attendee_payment, :value => Addtl_attendee_charge %>
(Addtl_attendee_charge comes from a config file) (Addtl_attendee_charge来自配置文件)
and in my javascript file, I have the following: 在我的javascript文件中,我有以下内容:
function display_value() {
var a = $("#addtl_attendee_payment");
alert(a.val());
}
and in another spot in my new.html.erb, I have the following: 在我的new.html.erb的另一个地方,我有以下内容:
<script><%= "display_value()" %></script>
When I run this, I get "undefined" inside the alert box. 当我运行它时,我在警告框内得到“未定义”。 If I look at the HTML (using firefly), here's what I get: 如果我查看HTML(使用firefly),这就是我得到的:
<input id="payment_addtl_attendee_payment" type="hidden" value="500" name="payment[addtl_attendee_payment]">
Payment is the model name. 付款是型号名称。 This is the same type of code that worked for the test code. 这是适用于测试代码的相同类型的代码。 Any ideas? 有任何想法吗?
Note again that the model name is Payment, and although I did not add payment to the attribute name, Rails added it automatically. 再次注意,型号名称是Payment,虽然我没有向属性名称添加付款,但Rails会自动添加它。 I did try another variation on the javascript file: 我确实在javascript文件上尝试了另一种变体:
function display_value() {
var a = $("#payment_addtl_attendee_payment");
alert(a.val());
}
But that did not work either (getting the same message). 但这也不起作用(获得相同的信息)。 I think that adding the payment_ is normal and is done by Rails (but I could be wrong, being a newbie) 我认为添加payment_是正常的并且由Rails完成(但我可能是错的,作为新手)
请注意,渲染标记中有不同的ID:
var a = $("#payment_addtl_attendee_payment");
Hi if your ID is fixed then you can use 嗨,如果您的ID已修复,那么您可以使用
var a = $("#payment_addtl_attendee_payment");
for getting the value , or you can go with this piece of code 获取价值,或者你可以使用这段代码
var a = $("#_addtl_attendee_payment");
why can't you add a unique class attribute for the hidden field and access the value through it. 为什么不能为隐藏字段添加唯一的类属性并通过它访问值。
<%= f.hidden_field :addtl_attendee_payment, :class="some_unique_class_id", :value => Addtl_attendee_charge %>
And you can access the value as below. 您可以访问以下值。
function display_value() {
var a = $(".some_unique_class_id");
alert(a.val());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.