MaryAnn
MaryAnn

Reputation: 85

How to change input field using javascript onclick?

Is it possible to change input field using javascript onclick?? My code:

<form>
 <input type="text" id="demo" value="John">
</form>
<button onclick="myFunction()">Click me!</button>  
<script>
  function myFunction() {
    document.getElementById("demo").value = "Hello World";
  }
</script>

it is successful to change the text, but it is failed to change input field value anyidea how to solve it??? Thank you very muchenter image description here

Upvotes: 1

Views: 2626

Answers (1)

wangdev87
wangdev87

Reputation: 8751

To update the value field of the HTML as well, use setAttribute()

<form>
 <input type="text" id="demo" value="John">
</form>
<button onclick="myFunction()">Click me!</button>  
<script>
  function myFunction() {
    document.getElementById("demo").setAttribute("value", "Hello World");
  }
</script>

Upvotes: 1

Related Questions