1

Example:

<button type="button" value="5">5</button>

What I'm trying to do is create a javascript calculator. When the button is pushed, I would like to be able to display that value. Currently, I cannot seem to figure out how to retrieve the value and am unsure if it's valid to use a number.

EveG
  • 15
  • 5
  • So many ways to solve it without attributes. Here's one: https://jsfiddle.net/c29g0ud6/2/ – NicklasF Sep 09 '20 at 21:26
  • Does this answer your question? [On click get button Value](https://stackoverflow.com/questions/16756048/on-click-get-button-value) – Heretic Monkey Sep 09 '20 at 21:31
  • That question's answers show how to get the value of the button. Anything that is valid in an attribute value, is valid in the `value` attribute's value. – Heretic Monkey Sep 09 '20 at 21:34
  • A HTML attribute is always a string. Of course you can store a numeric one. – Bergi Sep 09 '20 at 21:39
  • @HereticMonkey, it answers part of the question, but doesn't speak to whether value can be an integer. – EveG Sep 09 '20 at 22:45
  • As I said in my comment, you can set the value to any value an attribute is settable to. There's no need to answer that part of the question; a simple perusal of, say, [MDN's documentation of the attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes) will confirm what I and others have said. – Heretic Monkey Sep 09 '20 at 23:44

4 Answers4

1

According to W3Schools

value: text

This means "value" attribute always receives a text (string).

You can always parse the number if in need.

i.e.

// having myButtonValue as the value from button
var number = +myButtonValue
Alexander Santos
  • 1,458
  • 11
  • 22
0

Try using an input instead:

<input id="b5" type="button" value="5" />

you can then parse the value into a number:

const value = document.getElementById("b5").value;
0

In this case it would be most appropriate to use the data attribute .. Like so:

 <button type="button" data-value="5">5</button>

Then you can retrieve it simply using :

var el = document.querySelector('your_button');
console.log(el.getAttribute('data-value'));

NOTE That I am using querySelector as a generic term .. You could give it a class, name or ID -- And retrieve it IE getElementById()

Zak
  • 6,976
  • 2
  • 26
  • 48
-2

Any component can have any attribute, but the button for selecting integers values may not be the most HTML semantically correct.

Vitor Piovezam
  • 445
  • 3
  • 10