我的输入类型如下:
<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>
我的问题是,我想从多个选择选项中选择的选项中填充隐藏的输入。因此,请注意,所选的选项是&#39; email1&#39;,&#39; email2&#39;,&#39; email3&#39;然后会受到影响隐藏类型,例如电子邮件1,电子邮件2,电子邮件3和#39;。
我在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 ?
}
});
});
非常感谢您的帮助...
编辑以下是小提琴:JSFIDDLE
答案 0 :(得分:0)
现在更新了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);
});
评论版(用于学习和填充)
$("#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);
});