我试图得到一个标签来描述一个输入字段。我有这样的东西(这段代码在<c:foreach/>中)
<label for="some_input-${someCounter.index}">
The value in the associated input is: ${ $('#some_input-'+${someCounter.index}).val() }
</label>
<input id="some_input-${comeCounter.index}"/>我在试图使用jQuery从输入字段中获取值时遇到了问题。输入的id是使用.index设置的,这取决于循环的迭代,这给我带来了问题。我将有多个输入,每一个都有自己的标签。最终,这些标签将被隐藏在508。这就是为什么我需要从输入中获得值的主要原因。
需要澄清的编辑:I希望使用jQuery选择器从输入字段获取值,并在通过动态ID连接到它的标签中显示该值。
谢谢。
发布于 2015-05-26 18:49:13
要从输入字段中获取值,可以执行以下操作:
更新JSP:
<label for="some_input-${someCounter.index}">
The value in the associated input is: ${ $('#some_input-'+${someCounter.index}).val() }
</label>
<input id="some_input-${comeCounter.index}" class="some-class" />JavaScript示例:
$(".some-class").each(function() {
var $input = $(this);
// Now you can get the value of the input and do with it as you please.
console.log($input.val());
});澄清后的更新:
不,您不能在JSP中完成所有操作,因为您依赖于用户的输入;您需要绑定到change事件来更新该元素。有一种方法可以做到:
JSP:
<label for="some_input-${someCounter.index}">
The value in the associated input is: <output></output>
</label>
<input id="some_input-${comeCounter.index}" class="some-class" />JavaScript:
$(".some-class").on("change propertychange click keyup input paste", function() {
var $input = $(this),
id = $input.prop("id"),
$target = $('label[for="' + id + '"]').find("output") // Get the target element
// Update the target element
$target.text($input.val());
});这应该能起作用。您可以使用任何元素作为目标,它不需要是output元素。
注意:我更新了侦听器以获取多个事件,以便立即检测输入字段中的任何更改(而不是等待输入脱离焦点)。
https://stackoverflow.com/questions/30466419
复制相似问题