Dominique
Dominique

Reputation: 11

How to get onclick value in JS

Let's say, that I have on my site something like this:

<a href="" onclick="lol(222)">
<a href="" onclick="lol(223)">
<a href="" onclick="lol(212)">
<a href="" onclick="lol(122)">

And then I would like to parse it to get in the match variable all values in lol()

Like this:

match[0] = 222;
match[1] = 223;
.....

Upvotes: 1

Views: 1825

Answers (3)

DeveloperX
DeveloperX

Reputation: 4683

Your question isn't clear but i think this can be solution:

<a href="" onclick="lol(this,222)">
<a href="" onclick="lol(this,223)">
<a href="" onclick="lol(this,212)">
<a href="" onclick="lol(this,122)">
<script type="text/javascript">
function lol(sender,value) {
    //sender is clicked item
}
</script>

Upvotes: 1

pimvdb
pimvdb

Reputation: 154968

One way is a regular expression: http://jsfiddle.net/wtwzd/1/

var matches = [];
$('a').each(function() {
    matches.push(
        /lol\(([\d]+)\)/g
        .exec(
             $(this).attr('onclick')
        )[1]
    );
});
alert(matches);

Upvotes: 1

Andy E
Andy E

Reputation: 344783

The most cross browser approach is to use getAttributeNode, because jQuery's attr will have problems with IE7 and older:

var match = $("a[onclick]").map(function () {
    var onclick = this.getAttributeNode("onclick").nodeValue;
    return +onclick.slice(4, -1); 
}).get();

Working demo: http://jsfiddle.net/AndyE/Z2G2Z/

Upvotes: 6

Related Questions