Sylar Sylar - 4 months ago 23
Javascript Question

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
.

Answer

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();
Comments