skip to Main Content

Please check my code. The code adds the list item but it suddenly disappears. Kindly let me know the error in my code.

<button type="submit" class="btn btn-primary" id="needButton">Need</button>
<button type="submit" class="btn btn-primary btn-success" id="haveButton" >Have</button>
      </form>
      <div class="myNeed">
        <ul class="need">
        <li>
          The needed items are
        </li>
      </ul>
      </div>

This is js code

$(document).ready(function() {
  $("#needButton").click(function () {
    var needed = $("#bill").val();
    $(".need").append("<li>" + needed + "<li>");
  });
});

3

Answers


  1. The issue is because the button click triggers the form to be submit which redirects the page.

    To fix this, hook your event handler to the submit event of the form element and call preventDefault() on the event. Using this methoid over change the button type means that users can still trigger the action by pressing the return key on the keyboard when the input has focus.

    jQuery($ => {
      $("form").on('submit', e => {
        e.preventDefault();
        var needed = $("#bill").val();
        $(".need").append(`<li>${needed}</li>`);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <form>
      <input type="text" id="bill" />
      <button type="submit" class="btn btn-primary btn-success" id="haveButton">Have</button>
    </form>
    <div class="myNeed">
      <ul class="need">
      </ul>
    </div>
    Login or Signup to reply.
  2. i think there is a typo you write id=haveButton but in js code you type #needButton try change that to #haveButton

    Login or Signup to reply.
  3. i did a simple code for here i hop it will help you

    <button id="add">Have</button>
    <ul class="need"></ul>
    <script>
         $(document).ready(function () {
              $("#add").click(function () {
                   var needed = '123.';
                   $(".need").append("<li>" + needed + "</li>");
              });
         });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search