Skip to content
Advertisement

adding dynamically input box but it should stop base on the criteria,,,

elow is the code i am using i am able to add new input box wen i click but it should stop adding based on the user input like no. of user-entered as 4 based on that add input box should stop

in below example:-$bookcount is user input field which comes from html input box

var i = 1;
 
 if(i>$(bookcount))
 {
    $('#add').click(function()
    {
    i++;
    $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="title[]" </td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');

 }});

$(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id"); 
    $('#row'+button_id+'').remove();
});

$('#submit').click(function(){      
    $.ajax({
        url:"name.php",
        method:"POST",
        data:$('#add_name').serialize(),
        success:function(data)
**strong text**     {
            alert(data);
            $('#add_name')[0].reset();
        }
    });
});

enter image description here

Advertisement

Answer

Couple of issues to note:

  • Assuming bookcount is found from $("#bookcount") then you’ll need to get the .val() and convert it to a number (as “10”<“2”)
  • Check against bookcount value inside the click event:
var i = 1;
var bookcount = $("#bookcount");
 
$('#add').click(function() {
    if (i>(bookcount.val()*1)) {
        // do nothing
        return false; 
    }

    i++;
    $('#dynamic_field').append('<tr....
  • as you also have a remove function, don’t forget to reduce i when removing
$(document).on('click', '.btn_remove', function(){
    --i;

(in this case, I recommend something other than i, eg rowCount).


You can also do away with i (rowCount) by querying how many rows have been created dynamically:

var bookcountinput = $("#bookcount");

$('#add').click(function() {
    var rows = $("#dynamic_field tr").length;
    if (rows > bookcountinput.val()*1) 
        return;

    $('#dynamic_field').append('<tr....    
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement