LynAs
LynAs

Reputation: 6537

On click get button Value

I have a button like following

<input type='button' value='Generate' onclick='f1()' />

now the f1 function should show a alert box contain button value. in this case 'Generate'

How to do this?

I tried

alert(this);
alert(this.val());

it does not work

Upvotes: 8

Views: 98375

Answers (4)

Arunprasanth M
Arunprasanth M

Reputation: 73

HTML

 <div class="container">
          <button>7</button>
          <button>8</button>
          <button>9</button>
          <button>4</button>
          <button>5</button>
          <button>6</button>
          <button>1</button>
          <button>2</button>
          <button>3</button>
          <button>0</button>
        </div>
        <p id="calc"></p>

JS

let p = document.querySelectorAll("button");
p.forEach((btn) =>
  btn.addEventListener("click", (e) => {
    let display = document.getElementById("calc");
    display.innerHTML = e.target.innerHTML;
  })
);

Upvotes: 0

Mostafa Mohammadzadeh
Mostafa Mohammadzadeh

Reputation: 911

In case of using addEventListener() function:

button.addEventListener('click', (event) => {
    let value = event.target.value;
});

Upvotes: 1

amaugo somto
amaugo somto

Reputation: 462

Or you do this:

<button id='button' value='Generate' onclick='f1()'>Generate</button>

Then this for javascript:

Const click = document.getElementById('button')
Function f1{
  Alert(`${click.Value}`)
}

Upvotes: 2

codeandcloud
codeandcloud

Reputation: 55200

Try this.

<input type='button' value='Generate' onclick='f1(this)' />

Now alert like

function f1(objButton){  
    alert(objButton.value);
}

P.S: val() is actually a jQuery implementation of value

Upvotes: 29

Related Questions