向选定的弹出字段添加逗号
Add comma to Selected Pop Up Fields
>我从选择框 1 中选择多个字段,然后选择框 2。然后点击执行按钮,我的警报显示"动物鸟,狼狐"。我已经用谷歌搜索了如何在点击执行按钮时选择多个字段时添加逗号,但没有运气。我希望它读"动物,鸟,狼,狐狸"带逗号。下面是我的代码.html:
<select name="select1" id="select1" size="4" multiple>
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2" size="4" multiple>
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM</option>
</select>
<input type="button" id="button" value="Execute" />
JavaScript:
$("#select1").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and
kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
console.log(id);
var options = $(this).data('options').filter(function () {
return $.inArray(this.value, id) > -1
});
$('#select2').html(options);
});
$('#button').click(function() {
var str = $('#select1 option:selected').text() +','+ $('#select2 option:selected').text();
alert(str);
});
如果可能的话,我希望所选字段显示在执行按钮下方。
谢谢大家的帮助。
试试这个循环
http://jsfiddle.net/xd7pq22y/
$("#select1").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
console.log(id);
var options = $(this).data('options').filter(
function () {
return $.inArray(this.value, id) > -1
});
$('#select2').html(options);
});
$('#button').click(function() {
var values = [];
$('#select1 option:selected').each(function() {
values.push($(this).text());
});
$('#select2 option:selected').each(function() {
values.push($(this).text());
});
$("#wrapper").html(values.join(", "));
});
只需以整洁的方式执行此操作:
$('#button').click(function() {
var values = [];
$('#select1 :selected, #select2 :selected').each(function() {
values.push($(this).text());
});
alert(values.join(','));
});
我们在这里使用的是以下技术:
-
$().each()
方法:循环选择的元素集; -
Array.push()
方法:将一个字符串附加到数组一次; -
Array.join(separator)
方法:只需连接数组中的字符串;
相关文章:
- 使用单个文本框向多个字段添加严格搜索
- WooCommerce-根据自定义字段添加费用
- 向使用jQuery加载DOM后添加的字段添加不受限制的文本输入DatePickers
- j查询检查复选框是否被选中,然后向输入字段添加值
- 使用 javascript 将各种输入字段添加到一起
- 使用 jQuery 将字段添加到表中的 HTML 表单中
- 如何从动态输入字段添加数字
- Extjs 3.3动态地将字段添加到表单中,并设置它们的标签宽度
- JQuery:如何检查复选框是否被选中并向字段添加属性
- "未捕获的类型错误:未定义的不是函数“;当向输入字段添加值时
- Bootstrap typeahead为隐藏字段添加值
- 使用chrome扩展(HTML、CSS、JavaScript)向输入字段添加可点击的图标/按钮
- 正在向输入字段添加自定义验证
- 使用javascript向输入字段添加值
- 如何将自定义字段添加到Json结果-ASP.NET MVC
- 向选定的弹出字段添加逗号
- Accounts.onCreateUser 未将字段添加到 Meteor 的用户集合中
- 如何将自定义字段添加到 dhtmlxScheduler
- 根据 JavaScript 中的选中复选框将字段添加到页面
- 如何从开始日期中的单独字段添加天数/周,以在日期选择器中获取结束日期