How to add a new list element under a <ul> using jQuery?

jQueryJavascript

To add a new list element under a ul element, use the jQuery append() method

Set input type text initially

Value: <input type="text" name="task" id="input">

Now on the click of a button, add a new list element using the val() and append() methods in jQuery:

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

You can try to run the following code to learn how to add a new list element using jQuery:<./p>

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $('button').click(function() {
            var mylist = $('#input').val();
               $('#list').append('<li>'+mylist+'</li>');
               return false;
            });
         });
   </script>
</head>
<body>
   <form>
      Value: <input type="text" name="task" id="input">
      <button>Submit</button>
      <br>

      <p>Add a value above and click Submit to add a new list.</p>
      <ul id="list">
      </ul>
   </form>
</body>
</html>
raja
Published on 08-Aug-2018 08:52:07
Advertisements