Mumfordwiz
Mumfordwiz

Reputation: 1555

onclick passing on value of button

I want to send to my onClick function, the value of the button that pressed on it.

I have this function

numfunc = function (val) {
     var t = document.createTextNode(val);
     document.body.appendChild(t);
};

I have 5 buttons. I want them all to use this function onClick, but each send a different value,

their value.

var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";

var two = document.createElement("input");
two.type = "submit";
one.onclick = numfunc;
two.value = "2";

and so on....

I'm trying to do this, on javascript not on the html file.

Thanks!

Upvotes: 1

Views: 369

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You can use this.value to get value inside you function numfunc, you don't need to send parameter, check example bellow.

Hope this helps.


numfunc = function (val) {
  var t = document.createTextNode(this.value);
  document.body.appendChild(t);
};

var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";

var two = document.createElement("input");
two.type = "submit";
two.onclick = numfunc;
two.value = "2";

document.body.appendChild( one );
document.body.appendChild( two );

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

Can you use this code instead?

one.addEventListener("click", function () {
  numfunc(this.value);
}, false);

two.addEventListener("click", function () {
  numfunc(this.value);
}, false);

Upvotes: 1

Related Questions