Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - passing parameters to functions

This seems like a simple question, but I can't find a simple answer. So I'll start by giving a simple example.

<a href="#" onclick="showmsg('bark')">dog</a>
<a href="#" onclick="showmsg('meow')">cat</a>

And here's a javascript function...

function showmsg(msg) {
  alert(msg);
}

In the above example, additional content (lines of html) may be added without breaking the behavior (the javascript). Each line of html passes its own parameter to the javascript to tell it what message it should display.

If the html is changed to...

<a href="#" class="showmsg">dog</a>
<a href="#" class="showmsg">cat</a>

Then how do I write a jquery function that knows which line of html was clicked? In other words...

How do I pass a parameter to a jquery function?

like image 224
Audi Avatar asked Nov 11 '10 12:11

Audi


4 Answers

In this case I'd use a data- attribute, like this:

<a href="#" class="showmsg" data-sound="bark">dog</a>
<a href="#" class="showmsg" data-sound="meow">cat</a>

And your click handler can fetch it, like this:

$("a.showmsg").click(function() {
  alert($(this).attr("data-sound"));
});

Or in jQuery 1.4.3+

$("a.showmsg").click(function() {
  alert($(this).data("sound"));
});

You can test it out here.

To clarify based on comments: This is perfectly valid in HTML5, in HTML4 it's not valid, but the validator is the only issue you'll have, it'll work in every HTML4 browser. If it wasn't missing in HTML4, it wouldn't have been added in HTML5...I'd personally use it whether it validates or not.

like image 64
Nick Craver Avatar answered Sep 22 '22 10:09

Nick Craver


What you can do is to set a custom attribute that contains the value that needs to be pased to the function. Something like

<a href="#" class="showmsg" data-attr="bark">dog</a><br>
<a href="#" class="showmsg" data-attr="meow">cat</a><br>

$("a.showmsg").click(function(){
    var attr = $(this).attr("data-attr");
    return false;
});
like image 31
rahul Avatar answered Sep 19 '22 10:09

rahul


The data method is a good way to go. If it were me, though, I'd prefer not to have any HTML4 validation errors by defining the sounds in an object map, then pass the text to that map. For instance:

<a href="#" class="showmsg">dog</a>
<a href="#" class="showmsg">cat</a>
var sounds = {
    dog: "woof",
    cat: "meow",
    horse: "neigh",
    etc: "etc"
};
$("a.showmsg").click(function() {
    alert(sounds[$(this).text()] || "");
});

Working example: http://jsfiddle.net/AndyE/Q9yWU/

like image 44
Andy E Avatar answered Sep 22 '22 10:09

Andy E


Firstly to allow you to show code place the code in your post, select it and press ctrl+k to put in code block.

Back to question in jquery you use:

$("a.showmsg").click(function() {
    alert($(this).text());
});

You can use "this" to find out what has been clicked

like image 37
Scott Avatar answered Sep 21 '22 10:09

Scott