jQuery/JavaScript - get clicked button itself in a function

10,931

Solution 1

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/

Solution 2

Its better to remove the onclick from html and do the binding inside jQuery like

$(document).ready(function(){
    $('input[type="button"]').on('click', function(){
         $(this).prop('disabled', true);
  });
});

Check out this working fiddle.

Solution 3

Try this:

function x(elem){
    $(elem).prop("disabled",true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='button' onclick='x(this)' value='Disable me' />
<input type='button' onclick='x(this)' value='Disable me' />

Solution 4

You can get the element with jQuery in a few ways. In the case of your input tag, you can just say $('input'), but this will get all input elements. If you give it an id, like <input id="test" ...>, then $('#test') would work. Otherwise, $('input').prop('disabled',true); worked for me in Chrome.

Here's my full code:

<html>
<head>
</head>
<body>

    <input id="test" type='button' onclick='disable()' value='Disable me' />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    function disable() {
        $('#test').prop('disabled',true);
    }
    </script>
</body>
</html>

Solution 5

The one approach I can think of that doesn't require changing the HTML you're working with, but does involve changing the DOM you receive, is:

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

// selecting, and iterating over, all <input> elements with
// an in-line 'onclick' event-handler attribute:
$('input[onclick]').each(function() {

  // retrieving the contents of the 'onclick' attribute:
  var onClickFunction = $(this).attr('onclick');

  // setting the onClickFunction variable to the
  // substring of the existing value from the first
  // character to the index of the first '('
  // character, so from 'x()' to 'x' or from
  // 'function1();function2()' to 'function1'
  // (this could be worked-around, but this is
  // a simple proof-of-concept):
  onClickFunction = onClickFunction.substring(0, onClickFunction.indexOf('('));

  // if there is a function, or a variable, held as a
  // property of the window object, then:
  if (window[onClickFunction]) {
    // we remove the 'onclick' attribute, and use the
    // on() method to add the event-handler back:
    $(this).removeAttr('onclick').on('click', window[onClickFunction]);
  }
});

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

$('input[onclick]').each(function() {
  var onClickFunction = $(this).attr('onclick');
  onClickFunction = onClickFunction.substring(0, onClickFunction.indexOf('('));
  if (window[onClickFunction]) {
    $(this).removeAttr('onclick').on('click', window[onClickFunction]);
  }
});
<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' />

It's worth noting that, while the above is quite possible with jQuery, it's similarly possible with plain JavaScript:

function x() {
  this.disabled = true;
}

// excuse the absurdly-long variable-names; they were meant to be
// descriptive.
// here we retrieve all <input> elements with an onclick attribute:    
var inputsWithOnClick = document.querySelectorAll('input[onclick]'),

  // here we use Array.from() to turn that collection into an Array:
  arrayOfOnClickInputs = Array.from(inputsWithOnClick);

// iterating over the Array, 'input' (the first argument)
// refers to the current element of the array over which
// we're iterating:
arrayOfOnClickInputs.forEach(function(input) {

  // retrieving the contents of the 'onclick' attribute:
  var onClickFunction = input.getAttribute('onclick');

  // updating that variable to contain the substring of
  // of the attribute-value, from the first character to
  // the first occurrence of of the '(' character:
  onClickFunction = onClickFunction.substring(0, onClickFunction.indexOf('('));

  // as above:
  if (window[onClickFunction]) {

    // removing the 'onclick' attribute:
    input.removeAttribute('onclick');

    // using EventTarget.addEventListener to bind the
    // function to the click-event on the <input> element:
    input.addEventListener('click', window[onClickFunction]);
  }
});

function x() {
  this.disabled = true;
}

var inputsWithOnClick = document.querySelectorAll('input[onclick]'),
  arrayOfOnClickInputs = Array.from(inputsWithOnClick);

arrayOfOnClickInputs.forEach(function(input) {
  var onClickFunction = input.getAttribute('onclick');
  onClickFunction = onClickFunction.substring(0, onClickFunction.indexOf('('));

  if (window[onClickFunction]) {
    input.removeAttribute('onclick');
    input.addEventListener('click', window[onClickFunction]);
  }
});
<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' />

The reason for these approaches is simply that, in this case, the attribute is known (onclick), and you wanted to use this within the function, which jQuery manages for you, and which addEventListener() also does automagically.

And I honestly couldn't think of an alternative approach to supply the this to where you needed it to be.

References:

Share:
10,931
stramin
Author by

stramin

I am mainly a web developer (PHP, MySQL, JavaScript, CSS, etc). I am looking for get or give help, I like to help! It seems like I must write more lines here to earn a badge, but I don't want to bother you with irrelevant information, so I going to say I like to write if(condition){ in one line, I like play videogames and watch series like Walking Dead, House, Mr. Robot and Stranger Things. Ok, that wasn't enough either, how many info this badge need? If you continues asking me for info I going to explode, It feels like a psychologist meeting, well, you win, I hate anchovies, you got it, Is that what you wanted? Yep... I finally got the badge.

Updated on June 11, 2022

Comments

  • stramin
    stramin about 2 years

    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.