使用JQuery获取并选择多个值

Get select multiple values with JQuery

本文关键字:选择 JQuery 获取 使用      更新时间:2023-09-26

我对JQuery有一个问题,我有一个多选,我可以用两种方式填充,一种是用添加按钮手动从另一个select中获取一些值,另一种是动态解析从spring调用返回的json。当我手动添加值时,我可以接受它,但是,当我动态填充select时,JQuery代码不接受任何值,尽管在html代码中select中有值。

这是我的代码:

空的html选择

<div id="enti_disp_box">
  <label>Enti disponibili</label>
  <select id="ente" multiple> </select>
  <button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
  <label>Enti attivi*</label> 
  <select id="entiAttivi" multiple></select>
  <button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>

JQuery用于填充第二个手动选择

function addEnteInBox(){
   var selectedOptions = document.getElementById("ente");
   for (var i = 0; i < selectedOptions.length; i++) {
       var opt = selectedOptions[i];
       if (opt.selected) {
           document.getElementById("entiAttivi").appendChild(opt);
           i--;
       }
   }
}
function removeEnteInBox(){
   var x = document.getElementById("entiAttivi");
   x.remove(x.selectedIndex);
}

JQuery用于填充第二个动态选择

function getEntiByIdUtente(idutente) {
    var action = "getEntiByidUtente";
    var payload = {
        "idUtente": idutente,
        "action": action,
        "token": token
    };
    $.ajax({
        type: "POST",
        url: '../service/rest/enti/management_utenti',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(payload),
        resourceType: 'json',
        success: function(obj, textstatus) {
            obj = obj.trim();
            var json = JSON.parse(obj);
            //parse response
            if (obj.stato == 'error') {
                alert('Errore');
            } else {
                $('#entiAttivi').empty();
                //fetch obj.data and populate table
                $(json.data).each(function() {
                    $("#piva").val(this.piva);
                    $("#codiceipa").val(this.codiceipa);
                    $('#entiAttivi').append($('<option>', {
                        value: this.idente,
                        text: this.ragionesociale
                    }));
                });
            }
            return json;
        },
        error: function(obj, textstatus) {
            alert('Errore di comunicazione col server!');
        }
    });
}

JQuery获取第二个选择的值

var entiList = $("#entiAttivi").val();

这一行似乎错了,对我不起作用

$('#entiAttivi').append($('<option>', {
    value: this.idente,
    text: this.ragionesociale
}));

你能试着用代替吗

$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');

append试图创建一个以json为父的选项,但这不起作用。请试试我的代码。