向选定的弹出字段添加逗号

Add comma to Selected Pop Up Fields

本文关键字:字段 添加      更新时间:2023-09-26

>我从选择框 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(','));
});

我们在这里使用的是以下技术:

  1. $().each()方法:循环选择的元素集;
  2. Array.push()方法:将一个字符串附加到数组一次;
  3. Array.join(separator)方法:只需连接数组中的字符串;