I'm trying to call javascript function from a href . the function has a parameter which will be retrieved by the eval function . But some error occurs .
script:
function rate(id) {
// do something
}
the a tag that will call the function:
<a href="javascript:rate(" + <%#Eval("ID")%> + ")" >rate</a>
What am I missing ?
I'm trying to call javascript function from a href . the function has a parameter which will be retrieved by the eval function . But some error occurs .
script:
function rate(id) {
// do something
}
the a tag that will call the function:
<a href="javascript:rate(" + <%#Eval("ID")%> + ")" >rate</a>
What am I missing ?
Share Improve this question asked Jul 22, 2011 at 16:34 RoobahRoobah 3211 gold badge8 silver badges16 bronze badges 2- 1 What error? Why are you showing us server side code that generates JS instead of the generated JS? Why aren't you using progressive enhancement ? – Quentin Commented Jul 22, 2011 at 16:36
- @JAAulde the script does execute . If it is <a href="javascript:rate(5)" >rate</a> it executes . – Roobah Commented Jul 22, 2011 at 16:40
4 Answers
Reset to default 6You shouldn't be doing it like this, but the issue you're currently up against is probably is your quoting/concatenating.
If <%#Eval("ID")%>
simply produces an INT, this should work:
<a href="javascript:rate( <%#Eval("ID")%> )" >rate</a>
If it's a string,
<a href="javascript:rate( '<%#Eval("ID")%>' )" >rate</a>
should do it for you, although you need to handle the case of <%#Eval("ID")%>
producing anything with a single quote in it.
A Lesson:
I say you shouldn't be doing it like this because the javascript pseudo protocol (javascript:
) is defunct and improper. At worst you should be using an onclick
which returns false. Ideally you'd be assigning the event programatically and preventing the event object's default action.
I don't see any need for the use of eval() at all. Code in quotes like this is evaluated at the top level scope. If you make sure that both rate and ID are defined at that top level scope, then it will work without eval() with this HTML:
<a href="#" onclick="rate(ID);">rate</a>
and this code:
var ID = 3;
function rate(id) {
alert(id);
return(false);
}
You can see it work here: http://jsfiddle.net/jfriend00/bqqpM/. The trick to making this work without eval is just making sure that ID and rate are both available at the top level scope.
You shouldn't use " + + "
, because it will just be replaced with a number:
<a href="javascript:rate(<%#Eval("ID")%>)">rate</a>
Why call it as an href? You can just make a button and style it like a link. That would be a lot easier
<button id = "myButton" onclick = "rate(<%#Eval("ID")%>)" >rate</button>
#myButton
{
border: none;
padding: none;
background-color: transparent;
}