Reputation: 1325
In code behind I have the following code that gets the [IDphoto] from an SQL database. Now I want to send the IDphoto as a parameter to a jQuery function onClick. How can I do that?
Code behind
sb.AppendFormat("<a onclick='popup()' href='#" + IDphoto + "'>");
jQuery
function popup() {
$(document).ready(function () {
// Here I want to get the value of IDphoto ...
});
}
UPDATE
I've updated the codes based on TrueBlueAussie reply:
photos_sb.AppendFormat("<a href=\"#\" class=\"photo\" data-photo=\"" + IDphoto + "\">");
$(document).ready(function () {
// Here I want to get the value of IDphoto ...
$('a.photo').click(function(e){
// Stop the link click from moving to the page top
e.preventDefault();
var id = $(this).attr("data-photo");
alert(id);
});
});
Nothing is happening. The click doesn't fire the jQuery function!
Upvotes: 0
Views: 233
Reputation: 93571
A few words of advice:
onclick
attribute handlers with jQuery. That adds unneeded complexity and separation of the event code from the event registration code.data-
attributes to provide meta-data (rather than bury it in the href). Make the href a plain bookmark link (#).$(function(){...});
is a handy shortcut for $(document).ready(function(){...});
e.g
sb.AppendFormat("");
and add a jQuery click handler that looks for clicks on any .photo
links:
$(function () {
// Here I want to get the value of IDphoto ...
$('a.photo').click(function(e){
// Stop the link click from moving to the page top
e.preventDefault();
var id = $(this).attr("data-photo");
alert(id);
});
});
Here is a mockup of the above using some sample links:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/wqkxwz2j/
Upvotes: 2
Reputation: 8539
Not fully understand what you want. But here is example:
Code behind:
sb.AppendFormat("<a onclick='popup("+IDphoto +")' href='#'>");
Javascript
function popup(IDphoto) {
console.log(IDphoto);
}
Upvotes: 0
Reputation: 1624
why not just send the IDphoto to same popup function from your Code-Behind:
sb.AppendFormat("<a onclick='popup("+IDphoto+")' href='#" + IDphoto + "'>");
jQuery
function popup(myVarID) {
$(document).ready(function () {
// Here I want to get the value of IDphoto ...
});
}
Upvotes: 0