创建文本框并在页面加载时插入数据

时间:2016-08-23 14:20:52

标签: javascript jquery asp-classic

我想知道如何创建文本框并在页面加载时插入数据。

我要做的是从数据库中打开一个数组字符串,创建文本框并在页面加载时填充文本框。

我有一个来自ms sql数据库的数组字符串,看起来像这样

我用test,test;bla;bla2;test44;test55;test66 分隔每个单独的数组,我想创建文本框并将值一个接一个地插入到文本框中,因此最终结果如下所示:

enter image description here

我不知道如何使用以下代码执行此操作。

无论我尝试什么,我都搞乱添加/删除功能,或者在点击加号按钮时最终克隆所有文本框。

感谢

查看以下代码或转至https://jsfiddle.net/kj3cwww0

;

FORM SUBMIT CODE:

<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>

通过CLASSIC ASP呼叫:

<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>

1 个答案:

答案 0 :(得分:4)

这是一个有效的解决方案:

&#13;
&#13;
$(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();
    
});
&#13;
.entry:not(:first-of-type)
{
    margin-top: 10px;
}

.glyphicon
{
    font-size: 12px;
}
&#13;
<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>
&#13;
&#13;
&#13;

以下是我更改为您的代码的内容:

  • <script>的模板更改为<div>,默认情况下使用style="display: none;"隐藏它:

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

  • 初始化数组为空,以便我们可以放置自己的第一行:formArray = [ ],

  • 创建一个函数以在表单中添加字符串:

    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);
        }
     }
    
  • 最后,我添加了一些示例数据,然后按空行并更新表单:

    addToForm("2;3;4;5;6;7");
    formArray.push(clone($template));
    updateForm();
    
  • 编辑:我还删除了最后的模板div,以便在您提交时不会将其转入表单:

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

    为了能够做到这一点,我在开始时完全克隆了它:

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