How can I get ruby data to persist into javascript invoked events?
I'm having an issue with javascript variables. This is probably due to my lack of knowledge with scopes and which variable to use, although I tried the different variable types. (This is my first bit of actual javascript code). The way I see scopes in javascript is like this: If it's declared in a function you can't use it outside of the function. If you declare it first (outside of function) you can update the values in the function and use it outside, later in a different tag. Which I did.
What I'm doing: I am looping through a set of names that I get from a ruby model, here:
<% @items.each do |record| %>
Later in my code I open another script html tag inside of this .each:
<script> edit_items("<%=record.name%>") </script>
This 'edit_items' function gives me an array of all of the names of my record relations. (This is declared at the top of the page)
y=[];
function edit_items(x){
y.push(x);
}
The reason I'm looping through these items is to create listeners for each of the items(they're for users, so there will be a dynamic amount respective to each user). I have a ul with li elements with links to a modal pop-up (the html is on the same page).
What I'm trying to do is tell the javascript to set the value of the input (#name_box) in the modal to the information from the link clicked. Although there are multiple links for one textbox, so I have to specify which id will be sent to the box. At the bottom of the page:
$(document).ready(function() {
console.log("ready");
for (id = 0; id < y.length; id++){
console.log("starting li click events");
$("#" + y[id]).click(function () {
console.log("y: " + y[id]);
console.log("doc: " + document.getElementById(y[id]));
});
}
});
I'm creating event listeners for each link being created through this dynamic data from ruby array. Problem is: the action for the click is not ran until the page is on the client side. I'm thinking you can't get server side data (ruby) from client side listeners.
I get this in console.log when I click the links:
y: undefined
admin:318 doc: null
admin:317 y: undefined
admin:318 doc: null
which means, to me that y exists, but is not set and doc has no value (not finding the element with undefined data).
yprobably isn't available in the context in which you're trying to use it here. Where are you declaring thatedit_itemsfunction? Because unless it's globally declared, which you almost certainly don't want to do, then it won't be usable in that$(document).ready(function(){}.