Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add li element in ul using jquery

I try make simple todo list. This is my html code:

<form>
   Task: <input type="text" name="task" id="input">
   <button>Submit</button>
</form>

<br>

<h2>What you need to do</h2>
<ul id="list">

</ul>

Then I try use jquery to read from i input field and apppend to existing ul element. But when i try it in chrome my new added element show me for half of second and remove. Here is my js code:

  $(document).ready(function() {
    $('button').click(function() {
            var new_task = $('#input').val();
            $('#list').append('<li>'+new_task+'</li>');
    });
  });
like image 441
SuperManEver Avatar asked Dec 04 '22 10:12

SuperManEver


1 Answers

A button inside a form has a default type of submit, and will submit the form, you need to prevent that or set a different type on the button :

$(document).ready(function() {
    $('button').on('click', function(e) {
        e.preventDefault();
        var new_task = $('#input').val();
        $('#list').append('<li>'+new_task+'</li>');
    });
});
like image 100
adeneo Avatar answered Dec 07 '22 00:12

adeneo