dvdktn
dvdktn

Reputation: 63

store value from button in variable using javaScript

I have two buttons and I want to store the value attribute of the button pressed into a variable called amount. The code below is clearly wrong I have two identical id's for both buttons. What should I be doing in the function to save the value attribute to the variable amount onclick?

<button type="button" id='btn' onclick='storeVar' value='1'>1</button>
<button type="button" id='btn' onclick='storeVar' value='2'>2</button>
<script>
  function storeVar() {
    var amount = document.getElementById('btn').getAttribute('value');
    console.log(amount);
  } 
</script>

Upvotes: 0

Views: 8918

Answers (3)

Chayan
Chayan

Reputation: 614

Either give a unique id for each button or completely remove id attribute. After fixing your html try the following code.

<button type="button" id='btn' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>

<script>
    function storeVar(v){
        let amount = v;
        console.log(amount);
    }
</script>

Upvotes: 1

rohitwtbs
rohitwtbs

Reputation: 569

Make sure to have unique Id's.

<button type="button" id='btn-one' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>

<script>
function storeVar(value){
    let amount = value;
    console.log(amount);
}
</script> 

Upvotes: 1

Mamun
Mamun

Reputation: 68933

The attribute id must be unique in a document, use class instead. Also pass this to the function so that you can refer the current button inside the function:

function storeVar(el) {
  var amount = el.getAttribute('value'); 
  // OR: simply 
  // var amount = el.value;
  console.log(amount);
} 
<button type="button" class='btn' onclick='storeVar(this)' value='1'>1</button>
<button type="button" class='btn' onclick='storeVar(this)' value='2'>2</button>

Upvotes: 4

Related Questions