Reputation: 21
I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..." s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Upvotes: 3
Views: 189
Reputation: 150010
Your .innerHTML
setting is using s_d
, but your variable declaration has s_r
.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.
Upvotes: 1
Reputation: 28753
Since this is the value of a href
attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript:
protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Upvotes: 1
Reputation: 190897
Use a backslash like \'
.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Upvotes: 6