我有一個動態的表單,它計算持續時間。我可以通過點擊添加新行來插入行。 我的問題從無法計算的第二行開始,因爲它是動態的。你能幫我解決這個問題嗎?Javascript動態輸入計算
感謝
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var FieldCount = 1; //to keep track of text box added
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
FieldCount++;
wrapper.append('From → <input type="text" name="fromhours" id="fromhours' + FieldCount + '" onblur="cal()" /> : <input type="text" name="fromminutes" id="fromminutes' + FieldCount + '" onblur="cal()" /> | To → <input type="text" name="tohours" id="tohours' + FieldCount + '" onblur="cal()" /> : <input type="text" name="tominutes" id="tominutes' + FieldCount + '" onblur="cal()" /> | Result → <input type="text" name="resulthours" id="resulthours' + FieldCount + '" /> : <input type="text" name="resultminutes" id="resultminutes' + FieldCount + '" /><br /><br />'); //add input box
}
});
wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
function cal() {
var fromhours = parseInt(document.getElementById('fromhours').value) * 60;
var fromminutes = parseInt(document.getElementById('fromminutes').value);
var tohours = parseInt(document.getElementById('tohours').value) * 60;
var tominutes = parseInt(document.getElementById('tominutes').value);
var resultfrom = fromhours + fromminutes;
var resultto = tohours + tominutes;
var result = resultto - resultfrom;
var hourresult = parseInt(result/60);
var minutesresult = (result - (hourresult * 60));
document.getElementById('resulthours').value = '0' + hourresult.toFixed(0);
document.getElementById('resultminutes').value = ('0' + minutesresult).slice(-2);
}
input[type=text] {
width: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="margin-left:28px;" type="image" class="add_field_button" value="Add a new row" />
<br />From →
<input type="text" name="fromhours" id="fromhours" onblur="cal()" />:
<input type="text" name="fromminutes" id="fromminutes" onblur="cal()" />| To →
<input type="text" name="tohours" id="tohours" onblur="cal()" />:
<input type="text" name="tominutes" id="tominutes" onblur="cal()" />| Result →
<input type="text" name="resulthours" id="resulthours" />:
<input type="text" name="resultminutes" id="resultminutes" />
<br />
<br />
<div class="input_fields_wrap"></div>
我的問題是,從第二排,我不能讓我的結果工作
謝謝你的幫助 –