使用jQuery选择器更新元素

时间:2014-01-30 00:10:45

标签: javascript jquery

我有一种情况,我有以下表单元素:

<label for="edit-type-config-associated-element--2">Destination Data Element </label>
<input type="text" id="edit-type-config-associated-element--2"
   name="type_config[associated_element]" value="23" size="60" 
   maxlength="128" class="form-text ajax-processed" 
   style="visibility: hidden;">
<input type="text" id="edit-type-config-associated-element--2_display" 
   value="23" size="60" maxlength="128" 
   class="form-text ajax-processed dropdowntree_aux dropdowntree_input valid" 
   readonly="" style="top: 61.515625px; left: 15px; position: absolute; 
   width: 389px; height: 16px;">

我想在第二个输入元素中添加一个更改侦听器(由edit-type-config-associated-element-2_display标识),然后在第一个输入元素中更改输入(由edit-type-config标识) - 相关元件 - 2)。这里的问题是,每次显示这个表单时,两个ID末尾出现的数字都会增加1(为什么他们不能使用一致的id,我不知道,但这是我坚持的原因)。

以下是我用来尝试完成此操作的javascript:

// Add a change listener to associated element link for dc mappings
$('.dropdowntree_input').live('change', function () {
    // Get the data element id
    var dataElementID = $.trim($(this).val()),
        dataElementLinks = Drupal.settings.data_element_links;
    console.log('text field has changed to: ' + dataElementID);
    if (dataElementLinks.hasOwnProperty(dataElementID)) {
        $('#linked_form_elements').show();
    } else {
        $('#linked_form_elements').hide();
    }
    // Update the underlying text input to contain the right value.
    $(':input[type="text"][name="type_config[associated_element]"]').val(dataElementID);

然而这不起作用。似乎在更新第二个文本字段时从不调用此函数。

我已经脱离轨道的任何想法?

感谢。

1 个答案:

答案 0 :(得分:0)

您的选择器中似乎缺少[

$('input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
                     ^ here

此外,如果您使用的是jQuery&gt; = 1.9,则不再支持.live()。

如果您使用的是jQuery&gt; = 1.7,那么请使用.on(),因为第一个和第二个输入是next / prev兄弟,您可以使用该关系来查找元素

$(document).on('change', '.dropdowntree_input', function () {
    var dataElementID = $.trim($(this).val()),
        dataElementLinks = Drupal.settings.data_element_links;
    console.log('text field has changed to: ' + dataElementID);
    if (dataElementLinks.hasOwnProperty(dataElementID)) {
        $('#linked_form_elements').show();
    } else {
        $('#linked_form_elements').hide();
    }
    //since the hidden element is the previous sibling
    $(this).prev().val(dataElementID);
})