Add inputs according to the value of a field

Asked

Viewed 835 times

1

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

Ex: I have a number type field 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 value of the field 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.

  • You can wait for the event change in that input of a numerical type. Based on value of it, can make a loop to create the others inputs.

  • Where are the other inputs added? What type of input? The first is already added when the page loads or is created via Javascript?

  • @Sergio The first input is already created, the other inputs will be created on the same page and in the same form and will be text type.

  • @Darkmedia ok, and how is the HTML of the first input? has some particular class to be able to find it in DOM?

  • @Sergio At first there is no class to find it but there is no problem in adding one. the HTML of the first input currently looks like this: <input type="text" class="form-control" id="ncamisa" name="ncamisa" placeholder="Shirt size(s)">

1 answer

2


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

I also suggest giving an ID to this input type="numbver" so you can 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>
<input id="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: http://jsfiddle.net/29mb5zv1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.