Jorge Jorge - 10 months ago 49
jQuery Question

Prevent from adding/append input type="button" if submitted field is empty

I have this simple html project of adding list from inputted field

<div class="container">
<input id="list-input" />
<button id="add">Add To List</button>
</div>
<div class="container">
<h1>Your List</h1>
<ul id="mylist">

</ul>
<button id="clear">clear</button>
</div>


and below is how I manage my jquery in adding list

$('document').ready(function(){

//add to list function
$('#add').click(function(){
var newToList = $('#list-input').val();

$('#mylist').append('<li id="item">' + newToList + '<button id="remove"/></button>' + '</li>');

if(newToList == ""){
alert("Please input some list to do");

}

//clear input field
$('#list-input').val('');

});


});

Each time i submitted an empty field an alert will return but button i append still shows. Is there a way on how can i append the field value with a button next to it, where if the field is empty it wont show both field value and the button next to it?

SSA SSA
Answer Source

Return false after the alert.

$('#add').click(function(){
    var newToList = $('#list-input').val();

   if(newToList == ""){
        alert("Please input some list to do");
         return false;
    }
    $('#mylist').append('<li id="item">' + newToList  + '<button id="remove"/></button>' + '</li>');



    //clear input field
    $('#list-input').val('');

});