skip to Main Content

I want to add the amount put in a input field to a ul as list items.
I tried this but i can’t come further then this:

<body>
<input type="text" name="" id="txtNaam" placeholder="voer een getal in">
<div id="divResult"></div>
<ul></ul>
<script>
    $(document).ready(() => {
        var txtNaam = $('#txtNaam')
        $(document).on('click', function () {
            txtNaam.on('keypress', function (e) {
                var key = e.which
                if (key === 13) {
                    $('ul').append('<li>' + txtNaam.val() + '</li>');
                }
            })
        })
    })
</script>
</body>

So with txtNaam.val() if i write like 3 eggs for example in the txtNaam input field then eggs is added 3 times, is what i want to do.

Thanks already!

2

Answers


  1. Try This

      $(document).ready(function(){
            $('#txtNaam').on('keypress', function (e) {
              var txtNaam = $.trim(parseInt($('#txtNaam').val()));
              var key = e.which
              if (key === 13 && txtNaam != '') {
              for(var y = 0; y < txtNaam; y++){
                $('ul').append('<li></li>');
              }
             }
          });
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input type="text" name="txtNaam" id="txtNaam" placeholder="voer een getal in">
    <div id="divResult"></div>
    <ul></ul>
    Login or Signup to reply.
  2. You need to click enter key two times to check the snippet.

    You can use Regular Expressions to extract number string from the input value. Then parse it to int and use a for loop to carry the duplication.

    $(document).ready(() => {
      var txtNaam = $('#txtNaam');
      let numb;
        txtNaam.on('change', () => {
        if(txtNaam.val().match(/d+/)!=null){
     numb = parseInt(txtNaam.val().match(/d+/)[0]);
      }});
      txtNaam.on('keyup', function(e) {
    
        var key = e.which;
        if (key === 13) {
          if (numb >= 0) {
            for (i = 0; i < numb; i++) {
              $('ul').append(`<li>  ${txtNaam.val().replace(numb, '')}  </li>`);
            }
            numb=0;
          }
        }
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input type="text" name="txtNaam" id="txtNaam" placeholder="voer een getal in">
    <div id="divResult"></div>
    <ul></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search