1

I am trying to add users to the list using javascript, I dont know why my code is not working.

Here is my code.

HMTL

<form id="myform">
    <h2>Add a User:</h2>
    <input id="username" type="text" name="username" placeholder="name">
    <input id="email" type="email" name="email" placeholder="email">
    <button onclick='addUser()' type="submit">add user</button>
</form>

<h2>UsersList:</h2>
<ul id="users"></ul>

JavaScript

<script>
    var list = document.getElementById('users');
    function addUser(){
        var username =document.getElementById('username').value;
        var email = document.getElementById('email').value;
        var entry = document.createElement('li');
        entry.appendChild(document.createTextNode(username + '' + email));
        list.appendChild(entry);
    }
</script>
4

3 Answers 3

2

You need to handle form submit properly. Instead of button click event you would better listen onsubmit form event:

<form id="myform" onsubmit="return addUser()">

And from the function you need to return false to prevent form submission:

function addUser(){
    var username = document.getElementById('username').value;
    var email = document.getElementById('email').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(username + ' ' + email));
    list.appendChild(entry);

    return false;
}

Demo: http://jsfiddle.net/8846u/

Also note that making a button type button tag would also work but the best practice is actually to have type="submit". Benefits it provides is that you can submit a form with Enter key which is nice and consistent form behavior.

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

3 Comments

How to validate the email field using ajax?
I would recommend to ask it as a separate question, it's too broad to answer it in comments.
1

Try This

HTML

<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
 <button onclick='return addUser();' type="submit">add user</button>
</form>


<h2>UsersList:</h2>
<ul id="users"></ul>

JS

function addUser(){
    var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
    return false;
}

DEMO HERE

Comments

0

That button will submit the form, change the button type to button will fix it :

<button onclick='addUser()' type="button">add user</button>

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.