在多个元素上使用 jQuery 的 .val() [英] Using jQuery's .val() on multiple elements
问题描述
我正在使用 jQuery 的 .val()
将数据从我的 amCharts 周期选择器获取到我页面上的 div.它有效,但只带来一个值..amChartsInputField 有两个包含文本的输入区域.
我在 jQuery 文档中注意到 .val()
只适用于一个元素.有没有办法调整它以引入多个对象?
我的脚本如下:
jQuery:
chart1.addListener("rendered", function(e) {e.chart.periodSelector.addListener(已更改", function() {var date = $(".amChartsPeriodSelector .amChartsInputField").val();$("#date-div p").text(date);}}
HTML
拉取的信息
非常感谢您的帮助.
您可以使用 jQuery 的 map()
函数:
//对于每个匹配项,将值映射"到一个数组中var 日期 = $(".amChartsPeriodSelector .amChartsInputField").map(function() {返回 $(this).val();}).得到();//将值连接在一起并分配给 date-div$("#date-div p").text(dates.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!-- 组成适合您的选择器的 HTML --><div class="amChartsPeriodSelector"><input type="text" class="amChartsInputField" value="2014-10-10"/><input type="text" class="amChartsInputField" value="2015-11-10"/>
<div id="date-div"><p></p></div>
I am using jQuery's .val()
to get the data from my amCharts period selector to a div on my page. It works, but only brings in one value. The .amChartsInputField has two input areas that contain text.
I have noticed on the jQuery documentation that .val()
does only work with one element. Is there a way a way to tweak this to bring in multiple objects?
My script below:
jQuery:
chart1.addListener("rendered", function(e) {
e.chart.periodSelector.addListener("changed", function() {
var date = $(".amChartsPeriodSelector .amChartsInputField").val();
$("#date-div p").text( date );
}
}
HTML
<div id="date-div"><p>information pulled</p></div>
Your help is greatly appreciated.
You could collect all of the values into an array using jQuery's map()
function:
// for each match, "map" the value into an array
var dates = $(".amChartsPeriodSelector .amChartsInputField").map(function() {
return $(this).val();
}).get();
// join the values together and assign to the date-div
$("#date-div p").text(dates.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- made up HTML that fits your selectors -->
<div class="amChartsPeriodSelector">
<input type="text" class="amChartsInputField" value="2014-10-10" />
<input type="text" class="amChartsInputField" value="2015-11-10" />
</div>
<div id="date-div"><p></p></div>
这篇关于在多个元素上使用 jQuery 的 .val()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!