Reputation: 23
I am trying to pass a string into a function using the onclick Event. However when I click the link the variable inside the function returns nothing. It is empty. I have no issues when I pass a number as an argument and that is displayed in the alert with no issues. I am not sure what I am doing wrong.
for (var j=0;j<current_order.length;j++){
var note_id = "note" + (j+1);
text = text + "<button onClick= 'deleteItemfromOrder("+j+")'>Delete</button>";
text = text + "<a id = '"+note_id+"' onClick= 'toggleNote("+note_id+")'>Notes</a>";
alert(text);
}
This is the function I am trying to pass note_id to:
function toggleNote(showHideDiv) {
alert(showHideDiv);
}
I have tried multiple methods to pass the string as an argument to the function EG:
text = text + "<a id = '"+note_id+"' onClick= 'toggleNote('"+note_id+"')'>Notes</a>";
and
text = text + "<a id = '"+note_id+"' onClick= 'toggleNote(\'"+note_id+"\;)'>Notes</a>";
However every time the string appears empty on the other side in the function. There is no issues if I pass a number eg:
text = text + "<a id = '"+note_id+"' onClick= 'toggleNote("+2+")'>Notes</a>";
Upvotes: 1
Views: 732
Reputation: 318372
Your problem is that you're missing quotes, numbers don't need quotes, as in
onclick='toggleNote(3)'
but a string does
onclick='toggleNote("string")'
Also, using the same quotes won't work either
onclick='toggleNote('string')'
meaning you have to do
text = text + "<a id = '"+note_id+"' onClick= 'toggleNote(\""+note_id+"\")'>Notes</a>";
But really what you should do, is create elements
for (var j = 0; j < current_order.length; j++) {
(function(i) {
var btn = document.createElement('button');
var anc = document.createElement('a');
btn.addEventListener('click', function() {
deleteItemfromOrder(i);
});
btn.textContent = 'Delete';
anc.addEventListener('click', function() {
toggleNote("note" + (i+1))
});
anc.textContent = 'Notes';
})(j);
}
Upvotes: 1