I am trying to call a JavaScript function on click in a MVC2 View Page.
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>,<%=o.ba_Object_Code %>)" href="#">Select</a>
JavaScript function
function SelectBenefit(id,code) {
alert(id);
alert(code);
}
Here ba_Object_Id and Code are the values from the ViewModel. If I use SelectBenefit(<%=o.ba_Object_id %>)
in this way, its working fine. But when I have two paramaters its not.I am getting this error:
conditional compilation is turned off.
I think that you need to put quotes around the second parameter if it is a string:
<a onclick=" SelectBenefit(<%=o.ba_Object_id %>, '<%=o.ba_Object_Code %>')" href="#">Select</a>
This being said your parameters need to be properly encoded and I wouldn't pass them likse this. I would serialize them as JSON object to ensure that everything is OK. Like this:
<a onclick="SelectBenefit(<%= new JavaScriptSerializer().Serialize(new { id = o.ba_Object_id, code = o.ba_Object_Code }) %>)" href="#">Select</a>
and then the SelectBenefit function might look like this:
function SelectBenefit(benefit) {
alert(benefit.id);
alert(benefit.code);
}
I'm guessing o.ba_Object_Code
is not a number? Try putting quotes around it:
<a onclick="SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>')" href="#">Select</a>
You could also write this function like this:
<a href="javascript:SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>');">Select</a>
Or use Jquery (best approach, imo):
$('#yourlinkid').click(function(){
SelectBenefit(<%=o.ba_Object_id %>,'<%=o.ba_Object_Code %>');
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With