简体   繁体   中英

How to get value from a hidden_field_tag using data-id?

How do I get the value of an hidden_field_tag with data-id attribute?

html.erb

<%= hidden_field_tag "data-id" => 'cart-total', "value" => "#{total}" %>
#=> <input type="hidden" name="{"data-id"=>"cart-total", "value=>"1"}" id="__data-id__cart-total___value___1__">

JavaScript

var cartTotal = $("[data-id=cart-total]").val();
console.log(cartTotal); // undefined

I do not know the correct way to write this with rails hidden_field_tag .

Your element is wrong in the output, there is a object in name :

<input type="hidden" name="{"data-id"=>"cart-total", "value=>"1"}" id="__data-id__cart-total___value___1__">

I think it should be look like this ( i don't use rails ):

<%= hidden_field_tag "hidden", total, "data-id" => "cart-total" %>

And then you should use at least a better selector for the base element or something:

var cartTotal = $("input[data-id=cart-total]").val();

You haven't provided a name to your hidden_field_tag

<%= hidden_field_tag :field_name, "value" => "#{total}", "data-id" => 'cart-total', %>

Access it using data-id like this

var cartTotal = $("[data-id='cart-total']").val();

According to the documentation :

hidden_field_tag(name, value = nil, options = {})

Erb:

<%= hidden_field_tag :hidden, total, "data-id" => 'cart-total' %>

Js:

$("[data-id='cart-total']").val();

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