0

I want to change the label text once the user has changed the input field text.

This is what I have so far:

script function:

 function ModuleName() {
        var text = document.getElementById('txtModCode').innerHTML;
        document.getElementById('lblModCode').innerHTML = text;

    }

fields and label

<input type="text" name="txtModCode" id="txtModCode" class="form-control" placeholder="Enter Module Code Here" onchange="ModuleName()" />
<label id="lblModCode"></label>

Thank you in advance

2
  • 1
    So, what is wrong with what you have above? Commented May 7, 2018 at 19:21
  • 3
    inputs have value, not innerHTML Commented May 7, 2018 at 19:24

2 Answers 2

5

You should use .value in document.getElementById('txtModCode').value;, not .innerHTML

function ModuleName() {
  var text = document.getElementById('txtModCode').value;
  document.getElementById('lblModCode').innerHTML = text;
}
<input type="text" name="txtModCode" id="txtModCode" class="form-control" placeholder="Enter Module Code Here" onchange="ModuleName()" />
<label id="lblModCode"></label>


And by utilizing this in onchange="ModuleName(this)" you can pass a direct reference to the input and avoid the extra getElementById

function ModuleName(el) {
  document.getElementById('lblModCode').innerHTML = el.value;
}
<input type="text" name="txtModCode" id="txtModCode" class="form-control" placeholder="Enter Module Code Here" onchange="ModuleName(this)" />
<label id="lblModCode"></label>

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

Comments

0

To have a textbox that triggers a function when the contained text is changed use this:

 <body>
      <span id="thing2">you have not changed the textbox</span>
      <input type="text" id="thing" onchange="myFunction()">
 </body>
 <script>
      function myFunction(){
           document.getElementById("thing2").innerText = "you have changed the textbox"
      }
 </script>

This changes the contents of the element

1 Comment

This changes the label whenever you change the textbox, this does not make the label copy the textbox.

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.