1

I am having trouble outputing text to a div in Javascript. When I call the function on button click it displays the text for a fraction of second and then disappears. Why is it so? The code is given below;

Code:

function val(){
        var x = document.getElementById('us').value
        document.getElementById("demo").innerHTML = x;
}

HTML:

<form method="post">
   <p id="demo"></p>
   <br />
   <input type="text" id="us" name="username"></input>
   <br />           
   <button type="submit" onclick="val()">Sign Up</button>
</form>
3
  • 1
    i made a few changes from your code try this one jsfiddle.net/b19u9q4k Commented Sep 5, 2015 at 5:14
  • 1
    thats because of submit. Commented Sep 5, 2015 at 5:18
  • and if you are not using submit, then remove that method="post" attribute, because you are not submitting the form. Commented Sep 5, 2015 at 5:22

3 Answers 3

4
<form method="post">
   <p id="demo"></p>
   <br />
   <input type="text" id="us" name="username"></input>
   <br />           
   <button type="button" id="asd">Sign Up</button>
</form>

$('#asd').click(function () {
    var x = document.getElementById('us').value
        document.getElementById("demo").innerHTML = x;

});

FIDDLE

I made a few changes. I changed the button type from submit to button also i added an id for the button. check it

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

1 Comment

Any reason to prefer jQuery over vanilla js ?
3

You have a submit button in a form, its default action is to submit the form that is why the result is disappearing(the page is getting refreshed).

Since you really don't want to submit the form(here you are just doing some dynamic changes to the page), one easy solution is to change the type of the button to button

function val() {
  var x = document.getElementById('us').value
  document.getElementById("demo").innerHTML = x;
}
<form method="post">
  <p id="demo"></p>
  <br />
  <input type="text" id="us" name="username"></input>
  <br />
  <button type="button" onclick="val()">Sign Up</button>
</form>

Another solution is to prevent the default action of the submit button click by returning false

Comments

3

Try this:

Your code works as expected but as you have taken button type as submit, i submits the form.

function val() {
  var x = document.getElementById('us').value
  document.getElementById("demo").innerHTML = x;
}
<form method="post">
  <p id="demo"></p>
  <br />
  <input type="text" id="us" name="username"></input>
  <br />
  <button type="button" onclick="val()">Sign Up</button>
</form>

Comments

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.