AL-zami
AL-zami

Reputation: 9076

Does integer value behave as string inside input text field?

I am trying to convert decimal value to hexadecimal value using js. I have two input text fields here. One for input value and other for output value. I have tried something like this first:

<html>
<body>
<input type="text" placeholder="input hexadecimal" id='mytxt' width="300" height="200">
<input type="button" value="click me" id='mybtn'>
<input type='text' id='here' >
<script>
function init(){
  var field=document.getElementById('mybtn');
  field.addEventListener('click',getvalue,false);
}
function getvalue(){
var input=document.getElementById('mytxt');

var x=input.value.toString(16).toUpperCase();
alert(x);
var here=document.getElementById('here');
here.value=x;

}

window.onload=init;
</script>
</body>
</html>

It was not working. I mean the integer value remains same on the output, like if I tried 15000, it remains 15000.

Then I changed my code a little.

I parsed the input value using parseInt, then applied toString() method to it. Now it works as I expected like for 15000 it gives me 0x3A98 in hexadecimal.

var y=parseInt(input.value);
var x=y.toString(16).toUpperCase();

I have two questions regarding this post:

1. Why integer values act as a string value inside text field. Is it by default?

2. I have tried innerHTML to show value in the output text field. It didn't work. Why innerHTML method didn't work with input text field?

Upvotes: 1

Views: 284

Answers (2)

Enethion
Enethion

Reputation: 1257

  1. Yes. It is by dedault. JavaScript value always return string so (as Tiago Reis wrote) it's good practise to parse it to the type we need.

  2. innerHTML shows what's between opening and closing tag (e.g. <div><p>test</p></div> div's innerHTML is <p>test</p>). Value of <input> isn't inside of this tag and the tag itself is empty so using it will return empty string.

Upvotes: 1

Tiago Reis
Tiago Reis

Reputation: 74

The html input attrtibute value is a string type value.

So when used on javascript it's a best pratice to parse them to the type you want, like the parseInt to tell javascript this is a integer value.

can you show up the code of the innerHTML you are using?

Upvotes: 2

Related Questions