Jquery: Select the element that called the function
The solution is to store the dynamic value in a custom attribute, not an onclick handler. The HTML spec defines any attribute starting with "data-" as custom data used exactly for things like this, and it's in the spec so it will validate. So you can do something like this (using PHP for the example, adjust accordingly):
<input type="text" id="some-input" data-some-dynamic="<?php echo $something; ?>">
Then retrieve in the javascript 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 to using attribute handlers like onclick="", simple because it is more solid from a design perspective; separation of concerns and all that.
I doubt you genuinely do need to use an inline onclick
attribute. You can store data in an element in a variety of different ways. It's hard to say exactly how you would do it without knowing what the parameter you need to pass is, but I'll give some examples.
The most flexible would probably be in a data-
attribute:
<a href="#" id="subject" data-type="fiction">Text</a>
You could then access the information in the 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 classes, script tags that create global variables, all kinds of methods. These will almost certainly be better than putting jQuery handlers in onclick
attributes.
Try to send your element as a parameter to your function like that :
<input type="text" onclick="myfunction(this);"></input>
your function should be :
<script>
function myfunction(currentElement){
// ...
}
</script>