Home > Back-end >  Adding list items using jquery
Adding list items using jquery

Time:09-20

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"  id="needButton">Need</button>
<button type="submit"  id="haveButton" >Have</button>
      </form>
      <div >
        <ul >
        <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>");
  });
});

CodePudding user response:

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"  id="haveButton">Have</button>
</form>
<div >
  <ul >
  </ul>
</div>

CodePudding user response:

i think there is a typo you write id=haveButton but in js code you type #needButton try change that to #haveButton

CodePudding user response:

i did a simple code for here i hop it will help you

<button id="add">Have</button>
<ul ></ul>
<script>
     $(document).ready(function () {
          $("#add").click(function () {
               var needed = '123.';
               $(".need").append("<li>"   needed   "</li>");
          });
     });
</script>
  • Related