【问题标题】:Syntax for onchange event to update a hidden text box with the index value of a select box使用选择框的索引值更新隐藏文本框的 onchange 事件语法
【发布时间】:2012-09-13 10:02:05
【问题描述】:

我的意思是,我觉得自己完全是个白痴,但即使搜索了将近两个小时,我似乎也无法做到这一点。

此选择后跟一个隐藏的文本字段:

<select name="location_id" class="select green-gradient" single>
  <option value="2">New York</option>
  <option value="3">London</option>
  <option value="4">Singapore</option>
  <option value="5">San Francisco</option>
  <option value="6">Milan</option>
</select>
<input type='text'  name="selected_location_id" class="hidden" value="">

// 我通常将此代码用于复选框。它切换隐藏文本框的内容。我知道检查选择的值是不同的。但我似乎无法做到这一点。

$(document).ready(function(){
    $('.switch').change(function( ){
        if($(this).next().val() == 1){
            $(this).next().val(0);
        } else {
            $(this).next().val(1);
        }
    });
})

// 我试过这个:但它没有用,因为我需要对页面上的所有选择执行此操作。而且它仍然没有更新隐藏的文本框。

$(document).ready(function(){
   $('.select').change(function( ){
     var selectedValue = $(this "option:selected").val();
     $(this).next().val(selectedValue);
   });
})

// 也许我只是累了。但现在是寻求帮助的时候了。提前致谢。

【问题讨论】:

    标签: javascript html forms select hidden


    【解决方案1】:

    在侦听器中,this 引用该元素。您还可以从选择元素的名称中获取隐藏元素的名称,所以如果它们在表单中:

    this.form['selected_' + this.name].value = this.value;
    

    而且你没有一个函数调用就完成了。

    【讨论】:

    • 令人印象深刻。非常感谢。所以,this.form['my_text_box_name'].value=this.value;完美。
    【解决方案2】:
    var selectedValue = $("option:selected").val();
    

    通过取出“this”在 jsfiddle 中工作。

    【讨论】:

    • 如果页面中有6个select元素,每个元素都有一个selected选项,你会得到什么值?
    【解决方案3】:

    我觉得应该是

    $('select').change ///(without the dot)
    

    不是

    $('.switch').change
    

    都没有

    $('.select').change
    

    【讨论】:

    • 谢谢。所以 .syntax 解决了样式,没有点,输入的类型。谢谢。
    • 是的。这是正确的。所以,如果这解决了你的问题,你可以接受答案。
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多