gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:13:18 24 4
gpt4 key购买 nike

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

这还处于早期阶段,所以我只是想确保在继续页面功能之前创建了变量并且可以正确访问这些变量。我对网络开发很陌生,所以这些可能不是最好的方法。任何输入将不胜感激。

这是我的表格:

<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");

这是 fiddle :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 here .

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


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

关于javascript - 访问动态表单数组 HTML/Bootstrap/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com