访问动态表单数组 HTML/Bootstrap/Javascript

Accessing Dynamic Form Arrays HTML/Bootstrap/Javascript

本文关键字:Bootstrap Javascript HTML 数组 动态 表单 访问      更新时间:2023-09-26

>我正在尝试创建一个允许用户输入多个贷款的表单。 该表单有一行,输入余额、利率和最低还款额,单击 +/- 按钮将允许他们添加或删除行。 从视觉上看,该功能似乎还可以,但我正在尝试通过打印数组进行测试,但它失败了。

这是在早期阶段,所以我只是想确保变量正在创建并且可以在我进入页面功能之前正确访问。 我对 Web 开发生疏,所以这些可能不是最好的方法。 任何意见将不胜感激。

这是我的表格:

<form id="loanform" role="form" autocomplete="off" method="post" onsubmit="hello()">
                <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 class="entry input-group col-xs-9">
                    <div class="col-xs-3">
                        <input class="form-control" name="balances['+current+']" id="balances'+current+'" type="text" placeholder="Loan Balance" required="required" />
                    </div>
                    <div class="col-xs-3">
                        <input class="form-control" name="rates['+current+']" id="rates'+current+'" type="text" placeholder="Interest Rate" required="required" />
                    </div>
                    <div class="col-xs-3">
                        <input class="form-control" name="payments['+current+']" id="payments'+current+'" 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>
        <div class="input-group-btn">
            <div class="col-xs-5">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
        </form>

以下是用于创建新输入的 Javascript:

$(function () {
$(document).on('click', '.btn-add', function (e) {
    e.preventDefault();
    var controlForm = $('.controls form:first'),
        currentEntry = $(this).parents('.entry:first'),
        newEntry = $(currentEntry.clone()).appendTo(controlForm);
    newEntry.find('input').val('');
    controlForm.find('.entry:not(:last) .btn-add')
        .removeClass('btn-add').addClass('btn-remove')
        .removeClass('btn-success').addClass('btn-danger')
        .html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function (e) {
    $(this).parents('.entry:first').remove();
    e.preventDefault();
    return false;
});

});

这是我调用的函数提交:

function hello() {
alert("Hello has been called");
var bal = document.getElementById('balances0').value;
alert(bal);
alert("function over");

}

这是小提琴:http://jsfiddle.net/Afterbyrner/u55szysh/

你的代码中存在一些问题:

  1. hello不是一种全局方法。您可以像这样添加它window.hello = hello;然后就可以访问它了。但我建议使用$(...).submit(...)
  2. id="balances'+current+'"在 HTML 中无效。这不会被执行。
  3. 我会为每个输入字段添加类,并data-index以便于访问。
  4. 将表单存储在 DOM 中并不好,因为您无法保持索引干净。最好在 JS 中创建表单作为数组,并在每次 +/- 单击时更新此数组。我的意思是,例如,如果您添加了两行,那么第二行将具有data-index=1,如果您之前使用索引 0 删除 DOM 元素并重新添加一行,那么您的列表中没有索引 0。

你可以在这里找到更新的jsFiddle。

稍后我将改进代码以显示我对数组方法的含义。


更新 08.03.2015

请在此jsFiddle和下面找到更新的代码。

我添加了以下代码:

  • 跟踪数组中的表单元素
  • 将每行的表单元素作为模板存储在<script type="text/template"/>标记中。
  • 将数组项的索引添加到每个表单输入的 name 属性
  • 将对 $.submit(...) 内部表单数据的访问更改为$.serializeArray()
  • 添加新行后,向
  • 新输入行添加了焦点更改。

我认为这应该是您现在计算应用程序的一个很好的起点。

$(function() {
    //console.log($('#template_add_form'));
    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() {
        //console.log('clicked');
        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) {
            //console.log(index, row.has(evt.currentTarget).length);
            if ( row.has(evt.currentTarget).length == 1 ) {
                //console.log(row.has(evt.currentTarget));
                id = index; // click target in current row
                return false; // exit each loop
            }
        });
        
        //console.log('clicked', id);
        formArray.splice(id, 1);
        updateForm();
    });
    
    var updateForm = function() {
        // redraw form --> problem values are cleared!!
        //console.log(formArray);
        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) {
            //console.log(index, $input);
            // update names of inputs and add index
            //console.log('inputs', $input.find('input'));
            $.each($input.find('input'), function(inputIndex, input) {
                name = $(input).attr('name').replace(/'d+/g, ''); // remove ids
                $(input).attr('name', name + index);
            });
            
            if (index < lastIndex) {
                // not last element --> change button to minus
                //console.log($input.find('.btn-add'));
                $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
    
    $('form#loanform').submit(function(evt) { 
        evt.preventDefault();
        var fields = $(this).serializeArray();
        $.each(fields, function(index, field) {
            //console.log(field.name);
            if ( field.name == 'extra' ) {
                console.log('extra', field.name, field.value);
            }
            if ( field.name.contains('balance') ) 
            {   // field.name contains balance
                console.log('balance', field.name, field.value);
                // now you can do your calculation
            }
            if ( field.name.contains('rate') )
            {   // field.name contains balance
                console.log('rate', field.name, field.value);
                // now you can do your calculation
            }
            if ( field.name.contains('payment') )
            {   // field.name contains balance
                console.log('payment', field.name, field.value);
                // now you can do your calculation
            }
        });
    });
});
body {
    .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>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<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">
                <form id="loanform" role="form" autocomplete="off" method="post">
                    <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>
            </form>
            <br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
        </div>
    </div>
</div>