Динамическое заполнение опций выбора в родительском окне из дочернего всплывающего окна с помощью jQuery - PullRequest
1 голос
/ 08 мая 2019

Я пытаюсь заполнить параметры элемента select в родительском окне данными, возвращаемыми из вызова ajax, который вызывается из дочерней (всплывающей) формы.Дочерняя форма вызывается из родительского окна с помощью window.open.

Странно, что удаление опций выбора работает;это успешно выполняется:

$('#selElement', opener.document).find('option').remove().end();

Но добавление, как показано ниже, выдает SCRIPT5022: исключение выброшено и не перехвачено.

$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));

Я также пробовал

$('#selElement', opener.window.document).append($("<option />").val('').text('---Select---'));

вот код:

// the line below works; it removes all of the options from the drop-down
$('#selElement', opener.document).find('option').remove().end();

// the ajax call below returns the right data       
$.ajax({
    url: 'actions.cfc?method=getOptions&returnFormat=json',
    dataType: 'json',
    // the value being sent here just limits the options returned in the results
    data: {myType: $('#myType').val()},
    async:false,
    success: function(response) {
        // getting the right data back
        console.log(response);
        // the line below results in SCRIPT5022: Exception thrown and not caught
        $('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
        // never get this far unless I comment out the line above; then the error is thrown here    
        for (var i = 0; i < response.DATA.length; i++) {    
            $('#selElement', opener.document).append($("<option />").val(response.DATA[i][0]).text(response.DATA[i][1]));   
        }       
    },
    error: function (response) {
        var r = jQuery.parseJSON(response.responseText);
        alert("Message: " + r.Message);
    }
});

Есть идеи?

Ответы [ 3 ]

1 голос
/ 08 мая 2019

Если вы хотите создать элемент в другом document, вы должны указать его при создании, как и в цели:

$('#selElement', opener.document).append($("<option />", opener.document).val('').text('---Select---'));
//Specify the document where the element will be created ^ 

В противном случае элемент будет создан в дочернем документе, и при попытке кода добавить его в родительский документ возникнет ошибка.

Кроме того, вы можете упростить создание option:

$("<option value=''>---Select---</option>", opener.document)
1 голос
/ 08 мая 2019

Используйте .map, чтобы создать свой список параметров и добавить его для выбора тега.

const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
$('#selElement', opener.document).append('<select>' + option.join('') + '</select>')

const response = { DATA: [
  ['Mary', 'Mary'],
  ['Peter', 'Peter'],
  ['John', 'John'],
  ['Abel', 'Abel'],
  ['Mike', 'Mike']
]}


const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
option.unshift('<option>-----Select-----</option>');

 function myFunction() {
  const div = document.getElementById('test');
  div.innerHTML = ('<select>' + option.join('') + '</select>');
}
<button onclick="myFunction()">Try it</button>
<div id="test"></div>
0 голосов
/ 08 мая 2019

Это гибридное решение jquery / javascript, которое я иногда использую ...

    var mySubtype = document.getElementById("uploadSubtype");
    //Create arrays of options to be added        
    if(filetype == "2D"){
        var array = ['','Proofs','Graphic','Other'];
    } else if(filetype == "3D"){
        var array = ['','Prelims','Presentation','Controls','Final'];             
    } else if(filetype == "Accounting"){
        var array = ['','W-9','Other']; 
    }

    $( "#uploadSubtype" ).append("<span class='subtype_form_label'>Subtype</span>");
    //Create and append select list        
    var selectList = document.createElement("select");
    selectList.id = "subtype";
    selectList.name = "subtype";
    selectList.classList.add("form_field");
    mySubtype.appendChild(selectList);

    //Create and append the options
    for (var i = 0; i < array.length; i++) {
        var option = document.createElement("option");
        option.setAttribute("value", array[i]);
        option.text = array[i];
        selectList.appendChild(option);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...