Home > Mobile >  Increase div id number with new div fields
Increase div id number with new div fields

Time:05-15

The following script creates new input fields up to 4. I need to know how can I increase the ID also as follows..

with first click, "var fieldHTML" generate :

<div><input type="text" id="sPhone_1" value=""/><a href="javascript:void(0);" ><img src="remove-icon.png"/></a></div>

Second click: id="sPhone_2" Third click: id="sPhone_3" and so on..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    var maxField = 4; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><input type="text" id="sPhone_" value=""/><a href="javascript:void(0);" ><img src="remove-icon.png"/></a></div>'; //New input field html 
    var x = 1; //Initial field counter is 1

    //Once add button is clicked
    $(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x  ; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
        }
    });

    //Once remove button is clicked
    $(wrapper).on('click', '.remove_button', function(e){
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>

<div >
    <div>
        <input type="text" name="Phone" id="sPhone" value=""/>
        <a href="javascript:void(0);"  title="Add field"><img src="add-icon.png"/></a>
    </div>
</div>

CodePudding user response:

$(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x  ; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
            newId = 'sPhone_'   x;
            document.getElementById('sPhone_').id = newId;
        }
    });

Try this. This should post the div in the html with the initial id sPhone_, then it gets that element and replaces the id with your new created id.

Or you can create the string to append in the function like this:

$(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x  ; //Increment field counter
            var fieldHTML = '<div><input type="text" id="sPhone_"'   x   'value=""/><a href="javascript:void(0);" ><img src="remove-icon.png"/></a></div>'; //New input field html 
            $(wrapper).append(fieldHTML); //Add field html
        }
    });
  • Related