我制作了一个带有动态输入字段的表单,用于插入数字,其中第一个输入是静态的,其他 5 个是用脚本动态生成的。现在,我想将所有插入的数字加到第 7 个输入 id-ed #income_sum 中。一切都适用于静态输入字段,我检查了两个字段并且它有效,而且,它适用于我的示例中的那个静态字段。但我的问题是,当我在其中一个动态字段中输入一个数字时,它不会在#income_sum 中求和,并且它们在该静态字段中被赋予类 .income_count。
这是我的html:
<form class="form-horizontal" id="whereEntry" method='post' action=''>
<fieldset>
<div class="control-group">
<div class="controls controls-row">
<input type="text" class="span3 register_input" id="main_activity" name="main_activity" placeholder="Company's main activity">
<input type="text" class="span1 register_input income_count" id="income" name="income" placeholder="% of income">
</div>
</div>
<div class="control-group">
<div class="controls controls-row">
<div id="InputsIncomeWrapper">
</div>
</div>
<div class="row">
<input type="text" class="span1 register_input pull-right" id="income_sum" name="income_sum">
</div>
<div class="row">
<a href="#" id="AddMoreIncomeBox" class="btn btn-info pull-right"><i class="icon-plus"></i>Add More</a>
</div>
</div>
</fieldset>
</form>
计算脚本:
//calculation script
var $form = $('#whereEntry'),
$summands = $form.find('.income_count'),
$sumDisplay = $('#income_sum');
$form.delegate('.income_count', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
动态字段脚本:
//add dynamic field script
$(document).ready(function() {
var MaxInputs = 5; //maximum input boxes allowed
var InputsWrapper = $("#InputsIncomeWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreIncomeBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('\
<div>\
<input type="text" class="register_input span3"\
name="main_activity_'+ FieldCount +'" id="main_activity_'+ FieldCount +'"\
placeholder="Company´s other activity" style="margin:0px 15px 20px 0px"/>\
<input type="text" class="span1 register_input income_count" id="income_'+ FieldCount +'"\
name="income_'+ FieldCount +'" placeholder="% of income"\ style="margin:0px 15px 20px 15px"/>\
<a href="#" class="removeclass pull-left"><i class="icon-remove icon-remove-addincome"></i></a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
这是当前情况的jsfiddle:http: //jsfiddle.net/Uwbe6/
有人帮忙吗?我知道问题出在那些动态领域,但不知道如何解决。我的jsfiddle更新中可能的解决方案?
谢谢