-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
  • 669,327
  • 51
  • 454
  • 560
tk123
  • 1
  • 2

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
  • 319,460
  • 37
  • 290
  • 318
  • thank you but why is your so different than what they have on the jquery website? Are you sure this an efficient way to do this? – tk123 Apr 21 '20 at 16:57
  • @tk123 Where on the jQuery website is this? – j08691 Apr 21 '20 at 17:50
  • @tk123 It's hard to know what you mean without seeing the example, but it's likely because this is using string interpolation and arrow functions which are newer JS features than the jQuery docs shows. – Rory McCrossan Apr 21 '20 at 18:13