Lee m
Lee m

Reputation: 3

How to check if my button was clicked in JavaScript?

I want to call a JavaScript function test() when I press enter or I click a button but I don't know how to check if the button was clicked in test().

HTML Code :

<input id="data" type="text" name="data" value="" onkeypress="test()" /> 
<button id="button" type="submit" onclick="test()">button</button>

JavaScript :

function test() {
    let data = document.getElementById("data") ;
    let button = document.getElementById("button") ;
    if(data.onkeypressed = this.event.which === 13 || /*need to check if button was clicked*/) {
         ...
         ...
         ...
}

How do I do this in JavaScript ?

Upvotes: 0

Views: 987

Answers (3)

leonheess
leonheess

Reputation: 21361

You can pass this into test() and use it there:

function test(el) {
  let enter = el.id === 'data' && this.event.which === 13;
  console.log(`Called by ${el.id}${enter ? ' and Enter was pressed' : ''}.`);
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" />
<button id="button" type="submit" onclick="test(this)">Button</button>

Upvotes: 1

Anis R.
Anis R.

Reputation: 6902

Use the button's onclick event handler for that. It will be called every time the button is clicked:

Edit: You can also use the input's onkeydown event to see if the user pressed enter while the input box was selected.

var data = document.getElementById("data") ;
var button = document.getElementById("button");
button.onclick = function() {
  console.log("clicked!");
  test();
  //do something
}

data.onkeydown = function(e) {
  if(e.keyCode == 13) {
    console.log("ENTER IS PRESSED!");
    this.blur(); //de-selects the textbox
  }
}


function test() {
    //do something
}
<input id="data" type="text" name="data" value="" /> 
        <button id="button" type="submit" >button</button>

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36564

You can pass this to function and check the tagName

function test(e) {
    let data = document.getElementById("data") ;
    let button = document.getElementById("button") ;
    if(data.onkeypressed = this.event.which === 13 || e.tagName === "BUTTON") {
      console.log("button")
    }
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" /> 
        <button id="button" type="submit" onclick="test(this)" >button</button>

Upvotes: 2

Related Questions