user7275516
user7275516

Reputation:

Cant change textfield in javascript

I am writing a javascript program which is supposed to change the text of a textfield once submit button is clicked

<script>

function change()
{
    document.getElementById("set").value="helloworld";
}

</script>

the textfield and submit button:

<form>
Enter Text <input type="text" id="set" >
<input type="submit" value="Press here" onclick="change()" />
</form>

once I press submit it only displays an empty textfield. But when I remove 'form' it displays the correct result. Can anyone explain why ?

On a similar note can anyone explain why 'form' is important when we can collect data without it as well..

Thanks in advance...

Upvotes: 0

Views: 73

Answers (2)

sreeja seguro
sreeja seguro

Reputation: 16

Please change input type submit to button and then try.

Upvotes: 0

Rayon
Rayon

Reputation: 36609

On click of the submit button, form is being submitted and hence page is unloaded.

Prevent form submission.

function change(e) {
  e.preventDefault();
  //^^^^^^^^^^^^^^^^^^  
  document.getElementById("set").value = "helloworld";
}
<form>
  Enter Text <input type="text" id="set">
  <input type="submit" value="Press here" onclick="change(event)" />
</form>

Upvotes: 3

Related Questions