0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.