When all previous fields are filled, add new input field

dynamic, forms, javascript, jquery

Solution

Try the following code:

$(function(){
    $(document).on("change","input", function(){
        var allGood=true;
        var lastInputField=0;
        $("input").each(function() {
            if ($(this).val() =="") {
                allGood=false;
                return false;
            }
            lastInputField++;
        });

        if (allGood) {
            $("<span>" + lastInputField + "<input type='text' id='lastinputfieldId" + lastInputField +"'" +
              "name='lastinputfieldName" + lastInputField + "'></span>").appendTo("form");
        }
    });
});
​

Demo: http://jsfiddle.net/mzNtj/3/.

Problem

Here is my current HTML and CSS code: ``` <form method="post" id="achievementf1" action=""> <span>1.</span> <input type="text" name="achievement1" id="achievement1" /> <br /> <span>2.</span> <input type="text" name="achievement2" id="achievement2" /> <br /> <span>3.</span> <input type="text" name="achievement3" id="achievement3" /> <br /> <input type="submit" name="submit1" value="Registrate" /> </form> ​ ``` ``` #border #info-box #info #box input[type="text"] { float: left; margin-top: 10px; margin-bottom: 10px; height: 25px; width: 650px; outline: none; } #border #info-box #info #box input[type="submit"] { margin-left: 500px; margin-top: 10px; margin-bottom: 10px; height: 35px; color: #fff; font-size: 20px; border: 2px solid #fff; border-radius: 8px 8px 8px 8px; padding-left: 15px; padding-right: 15px; padding-top: 3px; cursor: pointer; }​ ``` You can see it in action at http://jsfiddle.net/mzNtj/2/. I'd like to know how I can automatically append a new input field when all the others have been filled. I have a basic idea, to read in each field's value and check it with an `if` statement. Then, if none are empty, add new one. Is this an appropriate way to check, or does anyone have any better ideas?

Original source