stramin stramin - 5 months ago 16
jQuery Question

jQuery/JavaScript - get clicked button itself in a function

I need a way to get the element pressed in a function called by that element, and disable it.

I tried using $(this), but is not working, this is my code:

<script>
function x(){
$(this).prop("disabled",true);
}
<script>
<input type='button' onclick='x()' value='Disable me' />
<input type='button' onclick='x()' value='Disable me' />




function x(){
$(this).prop("disabled",true);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='button' onclick='x()' value='Disable me' />
<input type='button' onclick='x()' value='Disable me' />





I want to avoid add and call an id, is there any way to do it?

Thank you!

-- edit --


  • I can not edit the input elements, they are in another file.

  • the JS code is called before the html file, and I can not edit the html file.


Answer

Solution 1 :

You can simply attach a click event handler which targets the input of type button and then use this to target the element from where the event was invoked.

<script>
$(document).ready(function(){
$("input:button").click(function()
{
  $(this).prop("disabled",true);
});
});
</script>
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />    

Example : https://jsfiddle.net/DinoMyte/jmLynLsg/1/

Solution 2 :

You can pass this keyword from your javascript function that would acts as a pointer to the element.

 <script>
function x(obj){
        $(obj).prop("disabled",true);
    }
</script>
<input type='button' onclick='x(this)' value='Disable me' />
<input type='button' onclick='x(this)' value='Disable me' />

Example : https://jsfiddle.net/DinoMyte/jmLynLsg/2/

Comments