当涉及到嵌套元素时,如何使用jQuery操作html表单?

How would I use jQuery to manipulate a html form when there are nested elements involved?

本文关键字:jQuery 何使用 操作 html 表单 嵌套 元素      更新时间:2023-09-26

我有一个空表单,需要根据条件动态地填充我称之为迷你表单的内容。例如,这可以是一个询问餐馆名称和位置的表单。现在,根据餐馆的数量(假设是"m"),我想在大表格"m"中添加要求名称和位置的小表格。如何使用jQuery创建这些小表单,这些小表单包含餐厅的名称和位置,并将它们附加到大表单中呢?html看起来像这样。但是我需要根据用户需要的表单数量动态地创建它,以及他是否需要任何表单。

编辑-我已经知道我们不能嵌套表单。我把内部的form元素重命名为div。

<form>
<div id = 1> 
Name: <input type = "text" name = "name"> 
Location: <input type = "text" name ="location>
</div>
<div id = 2> 
Name: <input type = "text" name = "name"> 
Location: <input type = "text" name ="location>
</div>
... 
</form>

首先,您需要查找用户输入餐馆数量的输入更改:

$('#noofrestaurants').change(function(){

然后需要循环遍历输入的数字并每次创建新的输入:

var restaurants = $('#noofrestaurants').val();
for (var i = 0; i < restaurants; i++){
$('#miniformcontainer').append('<input type="text" name="rest_name[]"/><input type="text" name="rest_loc[]"/>');
}
});

你可以尝试这样做:

    <script>
    function addMiniForms(n)
    {
        for (i=0; i<n ; i++)
        {
            var $div = $("<div id='" + i + "'></div>");
            var $labelName = $("<label for='name" + i + "'>Name</label>");
            var $inputName = $("<input type='text' id='name" + i +' />");
            var $labelLocation = $("<label for='location" + i + "'>Location</label>");
            var $inputLocation = $("<input type='text' id='location" + i +' />");
            $div.append($labelName);
            $div.append($inputName);
            $div.append($labelLocation);
            $div.append($inputLocation);
            $("#containerid").append($div);
        };
    };
</script>

我没有测试过这段代码,所以它可能需要一些调整

不能嵌套表单。如果您希望在表单中有重复的输入,请为它们指定数组样式的名称:

<div id = 1> 
Name: <input type = "text" name = "name[]"> 
Location: <input type = "text" name ="location[]">
</div>

后端应该将这些转换为数组。例如,PHP将用包含Name所有输入的数组来填充$_POST['name']

jQuery看起来像:

divnum++;
$("form").append("<div id='"+divnum+"'>Name: <input type='text' name='name[]'">Location: <input type='text' name='location[]'></div>");