我在这里发现了类似的问题,但对我来说没有任何作用.
有如下输入:
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
Run Code Online (Sandbox Code Playgroud)
试图让这些领域像:
$('input[name="pages_title[]"]')
Run Code Online (Sandbox Code Playgroud)
但有空结果:(
如何获得所有领域?我只能这样$('input[name="pages_title[1]"]')
97l*_*ave 97
$('input[name^="pages_title"]').each(function() {
alert($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
注意:与@epascarello一致认为更好的解决方案是在元素中添加一个类并引用该类.
Dem*_*tic 30
这通常适用于Checkboxes和Radio按钮......但是,每个名称应该相同.
<input type="text" value="2" name="pages_title[]">
<input type="text" value="1" name="pages_title[]">
var x = $('input[name="pages_title[]"]').val();
Run Code Online (Sandbox Code Playgroud)
这是"假设"以逗号分隔值获取所有字段.从来没有尝试过文本框,所以不能保证.
正如@John评论的那样:迭代它们.
$('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });
编辑:不仅如此,你只需回答OP问题,有时你需要教他们更好的方法.(对不起,如果这听起来很傲慢)
评论:将输入定义为
<input type="text" value="1" name="pages_title[1]">
<input type="text" value="2" name="pages_title[2]">
Run Code Online (Sandbox Code Playgroud)
打破数组,每个输入都有一个唯一的名称,因此,它不再是一个数组.
小智 22
使用map方法我们可以获得存储在数组中的输入值.
var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();
Run Code Online (Sandbox Code Playgroud)
epa*_*llo 13
var elems = $( "[name^='pages_title']" );
Run Code Online (Sandbox Code Playgroud)
但更好的解决方案是在元素中添加一个类并引用该类.它是一个更快速查找的原因.
Lim*_*isa 13
将输入名称放在单引号之间,以便将括号[]
视为字符串
var multi_members="";
$("input[name='bayi[]']:checked:enabled").each(function() {
multi_members=$(this).val()+","+multi_members;
});
Run Code Online (Sandbox Code Playgroud)
您可以为输入文本框提供类名,如下所示:
<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">
Run Code Online (Sandbox Code Playgroud)
并迭代如下:
$('input.pages_title').each(function() {
alert($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
我认为最好的方法是使用Propper Form并使用jQuery.serializeArray.
<!-- a form with any type of input -->
<form class="a-form">
<select name="field[something]">...</select>
<input type="checkbox" name="field[somethingelse]" ... />
<input type="radio" name="field[somethingelse2]" ... />
<input type="text" name="field[somethingelse3]" ... />
</form>
<!-- sample ajax call -->
<script>
$(document).ready(function(){
$.ajax({
url: 'submit.php',
type: 'post',
data: $('form[name="a-form"]).serializeArray(),
success: function(response){
...
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这些值将以PHP格式提供$_POST['field'][INDEX]
.