0

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>");
  });
});

1
  • 5
    Change <button type="submit" to <button type="button". Form is getting submitted currently. Commented Sep 20, 2022 at 7:53

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Good point #Accessibility :)
0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.