问题描述
考虑:
$("[id^='txtYear_']").val();
为什么这只给我在第一个输入框中输入的值,其ID与txtYear_相符?我想得到所有输入框的值,其ID以txtYear _开头。
Why is this only giving me the value entered in the first input box with an ID staring with "txtYear_"? I would like to get the values of all input boxes that have an ID that starts with "txtYear_".
推荐答案
返回找到的元素集合中第一个元素的值。如果你想要一组数值,你可以简单地使用 + :
$.fn.val returns the value of the first element in the collection of found elements. If you want an array of values you can simply use $.fn.map + $.fn.get:
var values = $("[id^='txtYear_']").map(function() {
return this.value
}).get()
注意: .get()
是必要的,因为$ .fn .map不返回数组,而是返回一个新的jQuery集合。
Note: .get()
is necessary because $.fn.map doesn't return an array, but a new jQuery collection.
检查所有值是否为空(不是)你可以借助:
To check that all values are not empty (not ""
) you can do something like this with the help of Array.prototype.every:
var allFilled = values.every(function(value) {
return value.trim()
})
如果你不喜欢不需要辅助值
数组你可以更简单:
If you don't need auxiliary values
array you can do it simpler:
var allFilled = $("[id^='txtYear_']").get().every(function(el) {
return el.value.trim()
}) // => true/false
这篇关于jQuery多个选择器与.val()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!