Add inputs according to the value of a field

1

I would like to know how to create input fields according to the value I add in a field.

Ex: I have a field of type number that has a minimum value of 1 the maximum value of 4 and the default value is 1:

<input type="number" min="1" max="4" value="1" />

Since the default field value is 1, an input field must be created, but if the user changes this value to 3, 2 more fields must be created totaling 3 fields.

    
asked by anonymous 19.04.2015 / 16:05

1 answer

2

You need an event sink in the input that indicates the amount of inputs, and when this value changes you can check how many inputs there are. I suggest you change name="ncamisa" to name="ncamisa[]" so that PHP can read these inputs in the same array.

I also suggest giving this input type="numbver" to find it more easily.

$('#numeros').on('change', function () {
    var nr = parseInt(this.value, 10);
    var inputs = $('[name="ncamisa[]"]');
    var dif = inputs.length - nr;

    if (dif < 0) {
        var input = inputs.eq(0).clone().attr('id', '');
        while (dif++ < 0) $(document.body).append(input)
    } else if (dif > 0) {
        inputs.each(function (i) {
            if (i >= nr) this.remove();
        });
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><inputid="numeros" type="number" min="1" max="4" value="1" />
<input type="text" class="form-control" id="ncamisa" name="ncamisa[]" placeholder="Tamanho da(s) camisa">

Example: link

    
19.04.2015 / 18:16