[ACCEPTED]-Jquery: Select the element that called the function-jquery

Accepted answer
Score: 28

Try to send your element as a parameter 2 to your function like that :

<input type="text" onclick="myfunction(this);"></input>

your function 1 should be :

<script>
  function myfunction(currentElement){
    // ...
  }
</script>
Score: 9

I doubt you genuinely do need to use an 12 inline onclick attribute. You can store data in 11 an element in a variety of different ways. It's 10 hard to say exactly how you would do it 9 without knowing what the parameter you need 8 to pass is, but I'll give some examples.

The 7 most flexible would probably be in a data- attribute:

<a href="#" id="subject" data-type="fiction">Text</a>

You 6 could then access the information in the 5 following way:

$(document).ready(function(){
    $('#subject').click(function(){
        $type = $(this).data('type'); // this works as of jQuery 1.4.3, otherwise $(this).attr('data-type');

        // do your handling here, using $type
    });
});

You could also do this using 4 classes, script tags that create global 3 variables, all kinds of methods. These 2 will almost certainly be better than putting 1 jQuery handlers in onclick attributes.

Score: 4

The solution is to store the dynamic value 11 in a custom attribute, not an onclick handler. The 10 HTML spec defines any attribute starting 9 with "data-" as custom data used exactly 8 for things like this, and it's in the spec 7 so it will validate. So you can do something 6 like this (using PHP for the example, adjust 5 accordingly):

<input type="text" id="some-input" data-some-dynamic="<?php echo $something; ?>">

Then retrieve in the javascript 4 like so:

$(document).ready(function() {
  $('#some-input').click(function() {
    // $(this) -- is the input element
    // $(this).attr('some-dynamic-attribute') -- contains the dynamic data you need
  });
});

I think this method is superior 3 to using attribute handlers like onclick="", simple 2 because it is more solid from a design perspective; separation 1 of concerns and all that.

More Related questions