У меня есть форма, и когда я ввожу число и "keyup", он должен отображать общее количество. Однако до тех пор, пока форма статична, она работает нормально, но если динамически сгенерировано, она не работает.
Я добавил ссылку js fiddle, Любая помощь, которую оценили
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line"> <a href="#" alt="close" class="btn-close" title="Remove"><img alt="remove" src="img/close.png" /></a>
<input class="input-text" name="product-code" type="text" placeholder="Product Code"></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product" disabled></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<p>Line below dynamically generated</p>
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line"> <a href="#" alt="close" class="btn-close" title="Remove"><img alt="remove" src="img/close.png" /></a>
<input class="input-text" name="product-code" type="text" placeholder="Product Code"></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product" disabled></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<br>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input id="btn-update" name="btn-update" type="button" value="Update"></input>
<!-- Clear All Button -->
<input id="btn-removeAll" name="btn-removeAll" type="reset" value="Remove All"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-total" type="text" placeholder="Order total" disabled></input>
</div>
Мой код
var productLines = $("div.product-lines"),
productLine = $("div.product-line"),
productPrice = $("input[name=product-price]"),
productCode = $("input[name=product-code]"),
productQuan = $("input[name=product-quantity]"),
updateTotal = $("input#btn-update"),
orderTotal = $("input[name=order-total]");
$(productLines).on("keyup", function (event) {
var sum = 0;
$(productPrice).each(function () {
sum += Number($(this).val());
});
$(orderTotal).val(sum);
});
Я новичок в JS.
Делегируйте событие в элемент с более высоким значением. Например, если ваш элемент form
обернут внутри элемента section
, вы можете вместо этого использовать:
$('section').on('keyup', 'div.product-lines', function(event) {
...
});
См. Документацию о делегировании событий для получения подробной информации о том, как делегирование работает в jQuery.
Также input
элементы самозакрываются. <input...></input>
недействителен и должен быть заменен на <input.../>
.
Чтобы связать события с динамически вставленными элементами, попробуйте:
$(document).on("keyup", "div.product-lines", function (event) {
Этот синтаксис связывает прослушиватель событий с самим документом, тогда как $(productLines).on("keyup", function (event) {
только привязывается к элементам, которые в настоящее время существуют на странице при $(productLines).on("keyup", function (event) {
этой строки кода.
После создания новой строки вам необходимо обновить productPrice
var.
productPrice = $("input[name=product-price]")