Leah
Leah

Reputation: 29

Should I use .innerText or .value in JavaScript?

There's a problem I've encountered but can't find explanation so far. The code is as follows:

let textbox = document.getElementById("textbox");
let result = document.getElementById("result");

function convertToCm() {
  value = textbox.value;
  result.innerText = +value * 2.54;
  document.body.appendChild(result);
}
<input id="textbox" type="text">
<button onclick="convertToCm()">Convert to cm</button>
<div id="result">result</div>

In the second line of the function, I tried to use textbox.innerText instead, however this gives me output of 0 of whichever number I put in the textbox. In the third line, I also tried to use result.value instead, but it would then output the same number I put in the textbox. I'm really confused.

I've tried looking on a search engine but haven't found an explanation so far. What can I try next?

Upvotes: 2

Views: 1147

Answers (2)

Oskar Grosser
Oskar Grosser

Reputation: 3454

Your textbox refers to an HTMLInputElement (or <input>), which is a void element. As such, its .innerText is always an empty string.
Converting an empty string to a number will evaluate to zero.

Instead, use .value to read or write to a form control's value (form controls are for example <input>, <select>, <textarea>).

To read or write a non-void element's text, use .innerText (or preferably .textContent, because reading from it doesn't cause a reflow). Your variable result references an HTMLDivElement—a non-void element.

In the second line you update result.innerText. This will be reflected in the DOM immediately.
Because result already exists in the DOM, and is updated as you wanted, it is actually unnecessary to reappend it.

Feedback:
I recommend to keep functionality purely in your <script> (or JS file) for maintainability. Using the onevent HTML attributes is (usually) deprecated. Instead, use addEventListener():

  • Allows multiple event listeners to be added.
  • Allows setting of options for the listener.
  • Easier finding of dead code.
  • The event object is always passed as the first argument, instead of having to manually pass it or use the deprecated window.event property.
  • Doesn't clutter the HTML.

Upvotes: 3

Ketan Kale
Ketan Kale

Reputation: 31

To get or set value from input field we need to use .value as you write textbox.value which is correct.

<input id="textbox" type="text">

To get or set value from common elements (it could be any element/tag) we use .innerText as you write result.innerText which is correct.

<div id="result">result</div>

Also you don't need document.body.appendChild(result); line in your code.

Upvotes: 3

Related Questions