-6ren">
gpt4 book ai didi

javascript - 填充从 jquery 上的选定多个选项中隐藏的输入类型

转载 作者:行者123 更新时间:2023-11-28 03:11:38 35 4
gpt4 key购买 nike

我有一个类型如下的输入:

<input class="emailSend" name="emailSend" type="hidden">

然后我有一个像这样的多选选项

<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>

</select>
</div>

我的问题是,我想从从多个选择选项中选择的选项中填充隐藏的输入。比方说,选择的选项是“email1”、“email2”、“email3”,然后会影响隐藏类型,例如“email1、email2、email3”。

我已经在 jquery 中尝试了 3 个小时,但我被卡住了。我的代码是这样的。

$("#email").change(function() {

var elements = $("#email option:selected").length;
var input = $(".emailSend");

$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {

input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?

}
});
});

非常感谢您的帮助...

编辑 这是 fiddle :JSFIDDLE

最佳答案

已更新 FIDDLE现在我明白你说的是看你制作的 fiddle 是什么意思了。

这实际上就是您需要做的...

已更新以在地址之间包含空格!

  $("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});

Commented Version (for learning and stuff)

   $("#email").on('change', function() {

//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';

//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');

//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {

//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';

});

//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);

//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);

});

关于javascript - 填充从 jquery 上的选定多个选项中隐藏的输入类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30270245/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com