I have a field into which a user can type a number. Depending on the number the user inputs, a number of additional input fields are presented via appending additional HTML to a subsequent div.

It works generally well, putting in "1" results in 1 field being added, however some numbers seem not to work: 1 = 1 field 2 = 2 fields 3 = 2 fields () 4 = 3 fields 5 = 3 fields () 6 = 4 fields

It's like certain numbers don't register, and for each one that doesn't subsequent numbers are n fields less than they should be, where n is the number of smaller numbers before that point which have not registered.

However putting in 7 sometimes then jumps it to a total correct value of 7 fields, ... I can't see pattern.

HTML
The input field to specify number of fields to be appended:

    <div class="number_input">
    <input  id="element_207" type="number" value="" name="q_207" /> 
    </div>'

    <div id="survey_details"></div>

The jQuery function designed to fire on blur or keyup or change of the above field, and add in the input HTML X number of times

$(function() {
    var input = $('HTML TO BE APPENDED GOES HERE');
    var newFields = $('');

    $('#element_207').bind('blur keyup change', function() {
        var n = this.value || 0;
        if (n+1) {
            if (n > newFields.length) {
                addFields(n);
            } else {
                removeFields(n);
            }
        }
    });

    function addFields(n) {
        for (i = newFields.length; i < n; i++) {
            var newInput = input.clone();
            newFields = newFields.add(newInput);
            newInput.appendTo('#survey_details');
        }
    }

    function removeFields(n) {
        var removeField = newFields.slice(n).remove();
        newFields = newFields.not(removeField);
    }
});
1

There are 1 answers

0
Peter van der Wal On BEST ANSWER

Your code works fine with a

var input = $('<div>Append</div>');

However if you have multiple elements in your input, like

var input=$('<div>Line 1</div><div>Line 2</div>'); 

Both element are counted, so your length will return 2 if you have added it only once. Have all elements in one single <div> and it wil work

var input=$('<div><div>Line 1</div><div>Line 2</div><div>');

http://jsfiddle.net/ZPUfy/