Wzap PepexD Wzap PepexD - 2 months ago 7
HTML Question

Input hidden with array value - Ruby on Rails

I'm trying to send an array for use in javascript from html with a Ruby's variable like this:

<% @data.each do |d| %>
<input type="hidden" id="name" value= "<%= d.name %>">
<% end %>


"data" is a variable of a model

def index
@data = organizations.all
end


in js i used a variable with id "name"

var nombre = document.getElementById("name").value;
var x = name;


I want that x is an array like:

["Org1","Org2","Org3"]


thanks for everything

Answer

You are creating X amount of fields with the same id. That's a problem, the ID should be unique. There is an alternative though, you can use A CLASS!

 <% @data.each do |d| %>
   <input type="hidden" class="js-names" value= "<%= d.name %>">
 <% end %>

Get the list of elements

// Array of elements
var elements = Array.prototype.slice.call(document.getElementsByClassName('js-names'));
var names = elements.map(function(element) { return element.value; });

However, a better approach is definitely using gon