gpt4 book ai didi

javascript - 字段的动态数量取决于另一个字段的值

转载 作者:行者123 更新时间:2023-12-03 08:12:09 25 4
gpt4 key购买 nike

我有表格,它看起来像这样:

<div class="fieldWrapper">
<label for="id_rooms">Rooms:</label>
<input id="id_rooms" type="number" name="rooms" min="1">
</div>

<div class="extrafieldWrapper">
</div>

我有一个脚本,可以根据字段“房间”的值添加或删除几个字段“成人”和“ child ”。现在我想对字段“children”做同样的事情:根据字段“children”的值,脚本应该添加或删除字段“children_age”。我试图像这样实现它,但这是行不通的。

$(function () {
$('#id_rooms').bind('blur keyup change', function () {
var n = $('#id_rooms').val() || 0;
$("input[id='id_form-TOTAL_FORMS']").attr('value', n);
$(".extrafieldWrapper").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children'/><div id='extrafieldWrapperChAge'></div>");
$("#id_form" + i + "children").bind('blur keyup change', function() {
var n = $("#id_form" + i + "children").val() || 0;
$(".extrafieldWrapperChAge").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapperChAge").append("<br/><label for='id_form-" + i + "-childrenage'></label><input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />");
}
});
}
});
});

我是java脚本的新手,你能告诉我我做错了什么吗?非常感谢。

最佳答案

提取您的内部代码并仅对 child 年龄字段使用一个事件处理程序。在下面的代码中,我将children_age类添加到输入字段,然后附加一个事件处理程序来监听具有该类的所有元素的更改。

注1:监听更改事件应该足够了。注 2:使用 on 而不是 bind,因为它是 jQuery 团队推荐的

$(function(){

$('#id_rooms').on('change', function(e){

var n = $('#id_rooms').val() || 0;
var html = "";

for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-adult'>Adult:</label>"
+ "<input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/>"
+ "<label for='id_form-" + i + "-children'>Children:</label>"
+ "<input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children' class='children_age'/>"
+ "<div class='extrafieldWrapperChAge'></div>";
}
$(".extrafieldWrapper").html(html);
});

$(".extrafieldWrapper").on('change', '.children_age', function(e){

// $(this) refers to the element that changed
var n = $(this).val() || 0;
var html = "";

for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-childrenage'>Age of child "+(i+1)+"</label>"
+ "<input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />";
}
//.next - finds the next occurrence that matches the selector
$(this).next('.extrafieldWrapperChAge').html(html);
});

});

关于javascript - 字段的动态数量取决于另一个字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098375/

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