Add li element to ul using jquery

I am trying to make a simple to-do 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 to use jquery to read from the input field I and the application to the existing ul element. But when I tried this in chrome, my new added item showed me half a second and deleted. Here is my js code:

  $(document).ready(function() { $('button').click(function() { var new_task = $('#input').val(); $('#list').append('<li>'+new_task+'</li>'); }); }); 
+4
source share
4 answers

The button inside the form has a default submit type and will send the form, you need to prevent this 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>'); }); }); 
+10
source

try it

HTML

 <form> Task: <input type="text" name="task" id="input"> <button>Submit</button> <br> <h2>What you need to do</h2> <ul id="list"> </ul> </form> 

Js

 $(document).ready(function() { $('button').click(function() { var new_task = $('#input').val(); $('#list').append('<li>'+new_task+'</li>'); return false; }); }); 

Demo

+3
source

You must return false; at the end of your function:

 $('button').click(function() { var new_task = $('#input').val(); $('#list').append('<li>'+new_task+'</li>'); return false; // This is new line of code }); 
+3
source

Hey Nikita, your code doesn’t have any error, but the fact is that when you click the button your javascript is working correctly, and also adds divs to the list, but similarly your page receives this message because of two main

 1) your button is not having id 2) your page containing form tag. 

I suggest you if the form tag is not needed, delete it or add an identifier to the button

-2
source

Source: https://habr.com/ru/post/1486973/


All Articles