-1

Have a simple input box and submit button to append item to list. I have the correct ID’s and selectors. How is set up is you click with “click” function and when it clicks it selects the ul with its id selector then append is used to add the item but nothing appears.

$(document).ready(function() {
  $("#somebutton1").click(function() {
    $("#someul1").append("<li>Appended item</li>");
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width" />
  <title>cfds</title>
  <link rel="stylesheet" href="img/bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />
</head>

<body>

  <form id="someform1" name="someformname1">
    <input id="someinput1" type="text">
    <input id="somebutton1" type="submit">
  </form>

  <br><br>

  <div id="somediv1">
    <ul id="someul1">
      <li>coffee</li>
      <li>milk</li>
      <li>tea</li>
    </ul>
  </div>

  <br><br>

  <script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
  <script src="img/popper.min.js"></script>
  <script src="img/bootstrap.min.js"></script>
</body>

</html>
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

The issue is because the button is in a form and clicking on it submits that form. To have the JS work as you expect you need to stop that form from submitting, which can be done by using a submit event handler and calling preventDefault() on the event which is raised.

In addition you can append the typed value by reading the val() of the field. You can also empty the field after the value is appended. Try this:

jQuery($ => {
  let $input = $('#someinput1');

  $("#someform1").on('submit', function(e) {
    e.preventDefault();
    let value = $input.val().trim();
    if (value)
      $("#someul1").append(`<li>${value}</li>`);

    $input.val('');
  });
});
<form id="someform1" name="someformname1">
  <input id="someinput1" type="text">
  <input id="somebutton1" type="submit">
</form><br /><br />

<div id="somediv1">
  <ul id="someul1">
    <li>coffee</li>
    <li>milk</li>
    <li>tea</li>
  </ul>
</div><br /><br />

<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339