Wzap PepexD Wzap PepexD - 18 days ago 5
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

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:


thanks for everything


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