Search code examples
phpjqueryvariablesiterated-function

How to sum two variables: constant and iterated in text input's "name"?


I have a function:

<?php $max = 5; ?>

<script type="text/javascript">
jQuery(function($) {
    var scntDiv = $('#div');
    var i = $('#div p').size() + 2;
    var x = <?php echo $max;?>;
    var a = 0;
    $('#add').click (function() {
        $('<p><input type="text" id="" name="field['+a+'][0]" value="" placeholder="" /><a href="#" id="delete">Remove</a></p>').appendTo(scntDiv);
        i++;
        a++;
        return false;
    });
    $('#delete').live('click',function() {
        if( i > 2 ) {
        $(this).parents('p').remove();
        i--;
        }
        return false;
    });
});
</script>

As you can see var x is constant and var a iterates in every click of add button. How to make these two variables sum each other with every iteration and to replace +a+ in name="field['+a+'][0]"?


Solution

  • So, to extract it from comments, the easiest solution in this case would be:

    Change:

    var a = 0;
    

    By

    var a = x;