使用$ {}的动态ID的JQuery选择器

时间:2015-05-26 18:42:19

标签: jquery

我正在尝试使用标签来描述输入字段。我有这样的东西(这段代码在<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从输入字段获取值时遇到问题。使用根据循环的迭代而改变的.index来设置输入的id的事实给了我一些问题。我将有多个输入,每个输入都有自己的标签。最终这些标签将被隐藏508.这是我需要从输入中获取值的主要原因。

编辑以澄清: 我想使用jQuery选择器从输入字段中获取值,并在动态ID连接到它的标签中显示该值。

感谢。

1 个答案:

答案 0 :(得分:1)

要从输入字段中获取值,您可以执行以下操作:

  1. 将类添加到输入字段
  2. 选择该课程并随意输入
  3. 更新了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元素。

    注意:我已经更新了侦听器以接收多个事件,以便立即检测输入字段上的任何更改(而不是等待输入失焦)。

相关问题