Skip to content
Advertisement

Js call function with arguments

I have created 4 buttons and every button with its own id and I have a function that displays the given element id. so I want to apply it on all this 4 buttons. what did I do wrong?

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

<script type="text/javascript">
    
function show_id(element){
    alert(element.id)
}

for(i=0; i!=document.getElementsByTagName('button');i++){

    target = document.getElementsByTagName('button')[i]
    target.onclick = show_id(target)

}

</script>
</body>
</html>

Advertisement

Answer

Do it as below –

function show_id() {
  alert(this.id)
}

var buttons = document.querySelectorAll("button");

for (var i = 0; i < buttons.length; i++) {
  buttons[i].onclick = show_id;
}
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

Passing arguments to onclick event –

Using HTML

function show(element, value) {
  console.log(element.id);
  console.log(value);
}
<button id='b1' onclick='show(this, "a")'>Click</button>

Using JS

function show(value, event) {
 console.log(value);
 console.log(event.target.id);
}

var button = document.getElementById("b1");

button.onclick = show.bind(this, "a");
<button id='b1'>Click</button>

But, as mentioned by @connexo, use addEventListener to bind DOM events.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement