Mitesh
Mitesh

Reputation: 1572

javascript innerhtml is not responding

I am trying to capitalize everything i type inside the text-input the caps function on js works fine which i can see on console but the innerhtml function is not changing the html file

function clr() {
  document.getElementById("box").value = '';
}

function caps() {
  var str = document.getElementById("box").value;
  console.log(str);
  var res = str.toUpperCase();
  console.log(res);
  document.getElementById("box").innerHTML = res;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>UI</title>
  <link rel="stylesheet" href="css.css">
  <script src="myscript.js"></script>

  <body>
    <div id="magic">
      <input id="box">
      <p id="pp">
        <button onclick="clr()">Clear It</button>
        <button onclick="caps()">Capitalize</button>
      </p>
    </div>
  </body>

</html>

here i can see caps function is working fine on console but not working in HTML file

Upvotes: 0

Views: 40

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

For <input type="text">there is no innerHTML, they have the value attribute for that (you actually used it in the caps function). This should work:

function clr() {
  document.getElementById("box").value = '';
}

function caps() {
  var str = document.getElementById("box").value;
  console.log(str);
  var res = str.toUpperCase();
  console.log(res);
  document.getElementById("box").value = res;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>UI</title>
  <link rel="stylesheet" href="css.css">
  <script src="myscript.js"></script>

  <body>
    <div id="magic">
      <input id="box">
      <p id="pp">
        <button onclick="clr()">Clear It</button>
        <button onclick="caps()">Capitalize</button>
      </p>
    </div>
  </body>

</html>

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65815

input elements don't have an .innerHTML property. They have a .value property.

Only elements that have an opening and closing tag can contain any HTML within them, so only elements like: <div>, <span>, <p>, etc. can utilize .innerHTML.

You accessed the value properly in your clr function.

function clr() {
  document.getElementById("box").value = '';
}

function caps() {
  var str = document.getElementById("box").value;
  console.log(str);
  var res = str.toUpperCase();
  console.log(res);
  document.getElementById("box").value = res;
}
    <div id="magic">
      <input id="box">
      <p id="pp">
        <button onclick="clr()">Clear It</button>
        <button onclick="caps()">Capitalize</button>
      </p>
    </div>

Upvotes: 4

Related Questions