如何将 jquery 多选下拉列表的选定值放入隐藏元素的 id 中

How can I put selected value of jquery multiselect dropdown into a hidden element's id

本文关键字:隐藏 元素 id jquery 下拉列表      更新时间:2023-09-26
如何将

jquery多选下拉列表的选定值放入隐藏元素的id中?我需要那个id是一个数组,这样我就可以将多选的选定值放入其中。

我尝试的是:

$( "#Myselect" ).change(function(){
    var str = "";
    $( "select option:selected" ).each(function() {
        str += $( this ).val() + " ";
    });
    document.getElementById("objecttype").value = str; 
}).trigger( "change" );
<html:hidden styleId="objecttype" property="objecttype" name="Myobjecttype"/>

但是对象类型只是一个 ID,而不是一个数组!

我假设您希望将此隐藏字段发布在某个地方并在以后使用(服务器端或其他)。看看这个小提琴:http://jsfiddle.net/hm71689h/它大致是你想要的。

考虑一下Haxxxton刚才所说的:您使用分隔符(在本例中默认为逗号)连接值。稍后需要将该值拆分为新数组。

此外,在您的代码示例中,您使用以下内容引用隐藏字段: document.getElementById("objecttype")但是你没有使用标识符,你使用了名称。尽管您可能认为它应该相同,但 ID 与元素的名称不同。

我认为你需要这样的smth:

.HTML:

<select name="choice" multiple id="mySelect">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<input type="hidden" name="myObjecttype" />  

.JS:

$('#mySelect').change(function(){
      //brand new array each time
    var foo = [];
      //fills the array
    foo = $("option:selected", this).map(function(){ return $(this).val() }).get();
      //fills input with vals, as strings of course
    $("input[name='myObjecttype']").val(foo);
      //logs an array, if needed
    console.log($("input[name='myObjecttype']").val().split(','));
});  

不要忘记隐藏的输入不能存储数组/对象数据,只能存储字符串。但是你可以很容易地制作数组。

请参阅工作 jsfiddle: http://jsfiddle.net/sfvx5Loj/1/