Crozen
Crozen

Reputation: 13

How to compare between two or more buttons in js?

I have two buttons in my html code. I want to call only one js function (no jQuery) for each buttons.

The function will have conditions. I want to know how to compare between which button is clicked by the user.

Example :

if (button 1 clicked) {
  block
} else {
  block
}

The other way is to make one function per button but I don't want to do this.

Thank you very much.

Upvotes: 0

Views: 1662

Answers (4)

Nikolay Ermakov
Nikolay Ermakov

Reputation: 5061

Expanding the @Dyrandz Famador answer into what you wanted in your question.

function myFunction(elem) { 
    switch(elem.id) {
       case '1':
       ... your code
       break;
       case '2':
       ... your code
       break;
    }
}

<button id='1' onclick="myFunction(this)">button 1</button>
<button id='2' onclick="myFunction(this)">button 2</button>

Upvotes: 1

blurfx
blurfx

Reputation: 1360

You can do that with this keyword. this will point button what you clicked.

$(document).ready(function(){
    $("button").click(function(){
    console.log();
    alert(this.innerHTML + " Clicked");
  })
});

Working fiddle

Upvotes: 0

repzero
repzero

Reputation: 8412

Like this?

function handler(el){
buttons[i].addEventListener('click',function(e){
if(e.target.innerHTML=='Button1'){
alert("I will execute everything when button1 is clicked")
}
if(e.target.innerHTML=='Button2'){
alert("I will execute everything when button2 is clicked")
}
if(e.target.innerHTML=='Button3'){
alert("I will execute everything when button3 is clicked")
}

},false)
}
var buttons=document.getElementsByTagName('button')
for(i=0;i<buttons.length;++i){
handler(i)
}
<button>Button1</button>
<button>Button2</button>
<button>Button3</button>

Upvotes: 0

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

As mentioned in the comment, Add the parameter this to know which button is clicked by getting its id.

function myFunction(elem) { 
    document.getElementById("demo").innerHTML = "ID:" + elem.id; 
}
<button id='1' onclick="myFunction(this)">button 1</button>
<button id='2' onclick="myFunction(this)">button 2</button>

<p id="demo"></p>

Upvotes: 1

Related Questions