0

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>
2
  • 4
    I have two identical id's for both buttons That is invalid HTML. Fix that first. You also need to invoke the functions properly in the attribute, or, even better, attach the listeners properly using Javascript instead. Commented Oct 7, 2018 at 4:43
  • They should not have the same value for attribute id Commented Oct 7, 2018 at 4:45

3 Answers 3

4

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>

Sign up to request clarification or add additional context in comments.

6 Comments

Why bother with .getAttribute('value'); why not just use el.value?
@NewToJS, I was trying not to change OP's code much ..... though added that as part of the answer........thanks.
Understandable but since your answer update I believe this is now a better solution. +1
@NewToJS, thanks for helping me to improve the answer :)
One last thing, you can no doubt remove the class attribute since it isn't really being used. Also, you are welcome :)
|
1

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> 

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.