I have the following view index.slim
with JS code.
- ind = 0
- enlace = []
h1 Posts
table
thead
tr
th Content
tbody
- @posts.each_with_index do |post,i|
- ind = i
- enlace[i] = "https://midominio.com/#{i}"
tr
td= post.content
td
a.mx-1.btn.btn-sm.btn-outline-warning href="javascript:copiaURL();" Copiar URL
td= i
javascript:
function copiaURL() {
var aux = document.createElement("input");
aux.setAttribute("value","#{enlace[ind]}");
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
alert("URL copiada\n#{enlace[ind]}");
}
I have a domain of a client with certain parameters, for purposes of the question I summarize the parameters with the index of the each_with_index helper, the problem I have is that it brings me the last value of the array and it does not bring me the selection I made, I attach an image which represents the problem I have.
I select index 4 (it can be any of the list) and it always brings me the last one.
How can I make it select the index I want?
The problem is that you are mixing variables from your slim template with javascript, which are evaluated at different times.
In other words, you are iterating
@posts.each_with_index
where each loop assigns a different value to your variableind
with 15 being the last value assigned. Then OUTSIDE the iteration block, you're assigningenlace[ind]
ieenlace[15]
to your js. In fact, if you go to review your source code in the browser, you will see that it will always print the same thing, because in the resulting js it was already evaluated as:A possible solution would be something like:
What would generate links of the type
onclick="copiaURL('https://midominio.com/1')"
.Then in the function receive the parameter like: