简体   繁体   中英

I am having trouble getting my text input to append <li> to a blank <ul> in my html

My end goal is to have whatever input the user submits append to a blank ul of the page. Once the item is appended I'd like the value of the text input to return to a blank text box. Attempting to create a to-do list pretty much. I am not getting errors on my console so I am not sure what I am doing wrong! Here is my HTML:

<div class="list">

    <h1>To Do List</h1>
<form>
<label> Things to Do:
<input id="item" type="text" name="item" placeholder="Items" />
<input id="submit" type="submit" value="Add to List"/></label>
</form>
<ul>
</ul>
<button id="clear">Clear List</button>
<button id="completed">Clear Completed Items</button>
</div>

Here is my JavaScript:

    $(document).ready(function(){
//this appends the input inside on an li inside the ul we created in the html
$("form").submit(function(event){
  e.preventDefault();
$("ul").append("<li>" + $("#item")[0].value + "</li>");
$("#item") [0].value="";

});

When I attempt this, I notice the value is being saved in the url but not appending to the ul.

The problem is that you are passing the event of event through your form handler, but attempting to prevent the submission with e . These two handlers need to have the same name. Simply updating your function to pass through e instead of event solves this problem:

 $(document).ready(function() { //this appends the input inside on an li inside the ul we created in the html $("form").submit(function(e) { e.preventDefault(); $("ul").append("<li>" + $("#item")[0].value + "</li>"); $("#item")[0].value = ""; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="list"> <h1>To Do List</h1> <form> <label> Things to Do: <input id="item" type="text" name="item" placeholder="Items" /> <input id="submit" type="submit" value="Add to List"/></label> </form> <ul> </ul> <button id="clear">Clear List</button> <button id="completed">Clear Completed Items</button> </div> 

Hope this helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM