7

I would like to know how can I create textboxes and insert data at page load.

What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.

I have an array string from an ms sql database that looks something like this

test,test;bla;bla2;test44;test55;test66

I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:

enter image description here

I don't know how to do it using the code below.

Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.

THANKS

SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0

<script type='text/javascript'>//<![CDATA[
 $(function() {
    var clone = function(tmpl) {
            return $((tmpl.clone()).html())
        },
        $template = $('#template_add_form'),
        formArray = [ clone($template) ], // init array with first row
        $formEntries = $('#entries');

    $(document).on('click', '.btn-add', function() {
        formArray.push(clone($template));
        updateForm();

        // set focus to adding row = last element in array
        $(formArray).last()[0]
            .find('input')
            .first()
            .focus();
    });

    // remove not working yet

    $(document).on('click', '.btn-remove', function(evt) {
        var id;

        // iterate over formArray to find the currently clicked row
        $.each(formArray, function(index, row) {
            if ( row.has(evt.currentTarget).length == 1 ) {
                id = index; // click target in current row
                return false; // exit each loop
            }
        });
        formArray.splice(id, 1);
        updateForm();
    });

    var updateForm = function() {
        // redraw form --> problem values are cleared!!
        var lastIndex = formArray.length - 1,
            name; // stores current name of input

        $formEntries.empty(); // clear entries from DOM becaue we re-create them
        $.each(formArray, function(index, $input) {
            // update names of inputs and add index
            $.each($input.find('input'), function(inputIndex, input) {
                name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
                $(input).attr('name', name);
            });

            if (index < lastIndex) {
                // not last element --> change button to minus
                $input.find('.btn-add')
                     .removeClass('btn-add').addClass('btn-remove')
                     .removeClass('btn-success').addClass('btn-danger')
                     .html('<span class="glyphicon glyphicon-minus"></span>');
            }

            $formEntries.append($input);
        });
    };

    updateForm(); // first init. of form

});
//]]> 

</script>


<script id="template_add_form" type="text/template">
    <div class = "entry input-group col-xs-9">
        <div class = "col-xs-3">
            <input class = "form-control" name="balance" type = "text" 
                   placeholder = "Loan Balance" required = "required"/>
        </div>
        <div class="col-xs-3">
            <input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
        </div>
        <div class="col-xs-3">
            <input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
        </div> 
        <span class="input-group-btn col-xs-1">
            <button class="btn btn-success btn-add" type="button">
                <span class="glyphicon glyphicon-plus"></span >
            </button>
        </span>
    </div>
</script>


<div class="container">
    <div class="row">
        <div class="control-group" id="fields">
            <label class="control-label" for="field1">
                 <h3>Enter your loans below</h3>

            </label>
            <div class="controls">
                    <div class="entry input-group col-xs-3">How much extra money can you pay per month?
                        <input class="form-control" name="extra" type="text" placeholder="Extra/month">
                    </div>
                    <br>
                    <div id="entries"></div>
            </div>
            <div class="input-group-btn">
                <div class="col-xs-5">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
            <br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
        </div>
    </div>
</div>

FORM SUBMIT CODE:

<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">

<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>

CALLING IT VIA CLASSIC ASP:

if strComp(Request.Form("action"), "submit")= 0 then
 Response.write("IT WORKS")
end if
7
  • 1
    You should clean up your example so that the focus of the code is clear. There's no need for Bootstrap or Jquery includes, CSS, console logs, unrelated HTML, etc. Commented Aug 23, 2016 at 14:27
  • First of all remove the HTML code from the <script id="template_add_form" type="text/template"> tag. That is invalid. Insert it into a hidden div instead. Commented Aug 23, 2016 at 14:30
  • @ErikUggeldahl Clean-up done, Thanks. Commented Aug 23, 2016 at 14:39
  • @karacsi_maci I tried to change it to div but it stops to submit if I change it. Thanks Commented Aug 23, 2016 at 14:47
  • @karacsi_maci There's nothing wrong with having the template inside a script tag. Just means it will be ignored by the browser until it is actually used and added to the DOM Commented Aug 25, 2016 at 19:15

1 Answer 1

4
+50

Here is a solution that works :

$(function() {
    var clone = function(tmpl) {
            return $((tmpl.clone()).html())
        },
        $template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
        formArray = [  ], // init array enpty
        $formEntries = $('#entries');

    $(document).on('click', '.btn-add', function() {
        formArray.push(clone($template));
        updateForm();

        // set focus to adding row = last element in array
        $(formArray).last()[0]
            .find('input')
            .first()
            .focus();
    });

    // remove not working yet

    $(document).on('click', '.btn-remove', function(evt) {
        var id;

        // iterate over formArray to find the currently clicked row
        $.each(formArray, function(index, row) {
            if ( row.has(evt.currentTarget).length == 1 ) {
                id = index; // click target in current row
                return false; // exit each loop
            }
        });
        formArray.splice(id, 1);
        updateForm();
    });
    
    var addToForm = function (stringValue) {
        values = stringValue.split(";");
        for (var i = 0; i < values.length; i+=3) {
            var newLine = clone($template);
            var fields = newLine.find('.form-control');
            var toAdd = Math.min(values.length-i, 3);
            for (var j = 0; j < toAdd; j++) {
                 fields[j].value = values[i+j];
            }
            formArray.push(newLine);
        }
     }

    var updateForm = function() {
        // redraw form --> problem values are cleared!!
        var lastIndex = formArray.length - 1,
            name; // stores current name of input

        $formEntries.empty(); // clear entries from DOM becaue we re-create them
        $.each(formArray, function(index, $input) {
            // update names of inputs and add index
            $.each($input.find('input'), function(inputIndex, input) {
                name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
                $(input).attr('name', name);
            });

            if (index < lastIndex) {
                // not last element --> change button to minus
                $input.find('.btn-add')
                     .removeClass('btn-add').addClass('btn-remove')
                     .removeClass('btn-success').addClass('btn-danger')
                     .html('<span class="glyphicon glyphicon-minus"></span>');
            }

            $formEntries.append($input);
        });
    };

    addToForm("2;3;4;5;6;7");
    formArray.push(clone($template));
    updateForm();
    $('#template_add_form').remove();
    
});
.entry:not(:first-of-type)
{
    margin-top: 10px;
}

.glyphicon
{
    font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">

<div class="container">
    <div class="row">
        <div class="control-group" id="fields">
            <label class="control-label" for="field1">
                 <h3>Enter your loans below</h3>

            </label>
            <div class="controls">
                    <div class="entry input-group col-xs-3">How much extra money can you pay per month?
                        <input class="form-control" name="extra" type="text" placeholder="Extra/month">
                    </div>
                    <br>
                    <div id="entries"></div>
            </div>
            <div class="input-group-btn">
                <div class="col-xs-5">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
            <br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
        </div>
    </div>
</div>

<div id="template_add_form" type="text/template" style="display: none;">
    <div class = "entry input-group col-xs-9">
        <div class = "col-xs-3">
            <input class = "form-control" name="balance" type = "text" 
                   placeholder = "Loan Balance" required = "required"/>
        </div>
        <div class="col-xs-3">
            <input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
        </div>
        <div class="col-xs-3">
            <input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
        </div> 
        <span class="input-group-btn col-xs-1">
            <button class="btn btn-success btn-add" type="button">
                <span class="glyphicon glyphicon-plus"></span >
            </button>
        </span>
    </div>
</div>
</form>
</body>

Here's what I changed to your code :

  • Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :

    <div id="template_add_form" type="text/template" style="display: none;">

  • Initialized array empty, so that we can put our own first line : formArray = [ ],

  • Created a function to add a string in the form :

    var addToForm = function (stringValue) {
        values = stringValue.split(";");
        for (var i = 0; i < values.length; i+=3) {
            var newLine = clone($template);
            var fields = newLine.find('.form-control');
            var toAdd = Math.min(values.length-i, 3);
            for (var j = 0; j < toAdd; j++) {
                 fields[j].value = values[i+j];
            }
            formArray.push(newLine);
        }
     }
    
  • At the end, I added some example data, then pushed an empty line and updated the form :

    addToForm("2;3;4;5;6;7");
    formArray.push(clone($template));
    updateForm();
    
  • EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :

    $('#template_add_form').remove();

    To be able to do that, I cloned it entirely at start :

    $template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),

Sign up to request clarification or add additional context in comments.

8 Comments

If I change it from a <script> to <div> submit will not work unless I add this to the <button> onclick="$('form#loanform').submit();" but then the validation does not work. I will still mark your answer as correct as it will work using <script> vs <div> but I would also love to get <div> to work and sumbit correctly. I would be very happy if you can provide any further help on this.. Thanks
I edited my answer, now I think it works as you want. I delete the last div dynamically so it doesn't have to be a <script>.
Still the same. it will not submit unless I add onclick="$('form#loanform').submit();" to the submit button and if I add that then it does not validate the required fields.
Then I don't know what other code you have that forbids you to send. Are you sure you have no last empty line and all inputs are filled when trying to send ?
Because currently, in the code you provided, the "Submit" button already does nothing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.