Gloria
Gloria

Reputation: 1325

Send a dynamic parameter to a jQuery function from code behind

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

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

A few words of advice:

  • Do not use inline onclick attribute handlers with jQuery. That adds unneeded complexity and separation of the event code from the event registration code.
  • Use double-quote on HTML attribute values. Most browser accept either, but double-quoting is safer for compatibility.
  • Also use data- attributes to provide meta-data (rather than bury it in the href). Make the href a plain bookmark link (#).
  • Use a common class on any photo links to allow simpler jQuery matching (and styling):
  • $(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

aleha_84
aleha_84

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

Codeek
Codeek

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

Related Questions