[英]How can I put selected value of jquery multiselect dropdown into a hidden element's id
How can I put selected value of jquery multiselect dropdown into a hidden element's id? 如何将jquery multiselect下拉列表的选定值放入隐藏元素的ID中? I need that id be an array so I can get the selected values of the multiselect into that.
我需要将该id作为数组,以便可以将multiselect的选定值添加到该数组中。
What I tried is: 我试过的是:
$( "#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"/>
but objecttype is just an id and isn't an array! 但是objecttype只是一个id而不是一个数组!
I assume you want this hidden field to be posted somewhere and used later on (server-side or whatever). 我假设您希望将此隐藏字段发布到某个地方,然后在以后(服务器端或其他任何方式)使用。 Take a look at this Fiddle: http://jsfiddle.net/hm71689h/ it is roughly what you wanted.
看一下这个小提琴: http : //jsfiddle.net/hm71689h/大概就是您想要的。
Take into account what Haxxxton just said: you're joining the values using a delimiter (in this example a comma by default). 考虑到Haxxxton刚才说的内容:您正在使用定界符(在本示例中默认为逗号)连接值。 You need to split that value into a new array later on.
您稍后需要将该值拆分为一个新数组。
Also, in your code-sample, you're referring to the hidden field using: document.getElementById("objecttype")
But you did not use an identifier, you used a name. 另外,在代码示例中,您使用的是隐藏字段:
document.getElementById("objecttype")
但是您没有使用标识符,而是使用了名称。 Although you might think it should be the same, an ID is not the same as the name of an element. 尽管您可能认为应该相同,但是ID与元素名称不同。
I think you need smth like this: 我认为您需要这样的东西:
HTML: 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: 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(','));
});
Don't forget hidden input can't store array-/object- data, only strings. 不要忘记隐藏的输入不能存储数组/对象数据,只能存储字符串。 But you can easily make array.
但是您可以轻松地创建数组。
See working jsfiddle: http://jsfiddle.net/sfvx5Loj/1/ 参见工作jsfiddle: http : //jsfiddle.net/sfvx5Loj/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.