skip to Main Content

I have this code:

$(function() {
  var scntDiv = $('#p_scents');
  var i = $('#p_scents p').size() + 1;

  $('#addScnt').live('click', function() {
    $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
    i++;
    return false;
  });

  $('#remScnt').live('click', function() {
    if (i > 2) {
      $(this).parents('p').remove();
      i--;
    }
    return false;
  });
});
input {
  padding: 5px;
  border: 3px solid #999;
  border-radius: 8px;
  margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<button id="addScnt" style='margin-bottom: 15px;'>Add (limit 5)</button>

<div id="p_scents">
  <p>
    <label for="p_scnts"><input type="text" id="p_scnt" class="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
  </p>
</div>

I want to limit the creation of new inputs to 5 and create a unique id for each of them as they are generated, something like:

#myid1
#myid2
#myid3
#myid4
#myid5

This is a reproducible example only, I will need more fields for my real case.

$(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;

    $('#addScnt').on('click', function() {
        if (i <= 4) { // 5 inputs limit
            $('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" class="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
            i++;
        }
        return false;
    });

    $(document).on('click', '.remScnt', function() { 
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
}); 

But nothing else works. How to limit the number of entries created and assign a unique id to each of them?

2

Answers


  1. jQuery.size() has been removed with version 3.0. It has been replaced with jQuery.length. I changed line three of your code and now it works, as demonstrated below:

    $(function() {
     let scntDiv = $('#p_scents');
     let id=0, i = $('#p_scents p').length + 1;
    
    $('#addScnt').on('click', function() {
        if (i <= 4) { // Limita a 5 campos
            $('<p><label for="p_scnts"><input type="text" id="p_scnt_' + (++id) + '" class="p_scnt" size="20" name="p_scnt_' + id +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
            i++;
        }
        return false;
    });
    
    $(document).on('click', '.remScnt', function() { 
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
    });
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <button id="addScnt">add scent</button>
    <div id="p_scents">
    </div>

    I fixed the obvious bug with possibly repeating ids. It is just a quick fix, but it will guarantee unique IDs.

    Login or Signup to reply.
  2. Adding to the question based on Wimanicesir’s comments below the answer

    This Solution also does not use jQuery incase you wanted to see a different approach to the problem

    Shown in the snippet all functionality is generated using plain vanilla java script

    I’ve also added the containers ID to be displayed so you can see that they all have unique identifiers regardless of what one is removed

    All that is done is using one counter that increases infinitely to use as the ID and one counter that only increases to 5 to use as the count of current inputs, the MAX value can be changed to allow for more inputs

    const ADD_BUTTON = document.getElementById("AddScentButton")
    const ROOT = document.getElementById("root")
    const MAX = 5
    const PRE_ID = "MyID-"
    
    let input_count = 0
    let input_id = 0
    
    function createInput(id){
        let container = document.createElement("div")
        let input = document.createElement("input")
        let remove = document.createElement("a")
        let label = document.createElement("div")
        
        input.placeholder = "Input Value"
    
        remove.innerHTML = "Remove"
        remove.href = "javascript:;"
        remove.addEventListener("click",()=>{
            container.remove()
            input_count = input_count - 1
        })
    
        label.innerText = PRE_ID + id
    
        container.id = PRE_ID + id
        container.appendChild(label)
        container.appendChild(input)
        container.appendChild(remove)
    
        return(container)
    }
    
    ADD_BUTTON.addEventListener("click",()=>{
        if(input_count<MAX){
            ROOT.appendChild(createInput(input_id))
            input_count = input_count + 1
            input_id = input_id + 1
        }
    })
    <div id="root" style="display: flex; flex-direction: column; width: 25%;">
                <button id="AddScentButton">Add Scent</button>
            </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search