select option which were just appended with jquery

白昼怎懂夜的黑 提交于 2019-12-08 08:30:43

问题


Based on an AJAX query I appended some options to a list.

for(var i = 0; i < options.length; i++) {
    var data = options[i];
    var option = $('<option id="mySelectElementOption_' + data['id'] + '" value="' + data['value'] + '">' + data['value'] + '</option>');
    $('#mySelectElement').append(option);
}

Now when the user interacts on the page i want to select on of the just appended options and i tried the following (both possibilities don't work for me):

$('#mySelectElementOption_' + id).attr('selected', 'selected');

and

var option = document.getElementById('mySelectElementOption_' + id);
option.selected = true;

So I'm stuck, because I don't know how to select my option. Do you have any idea(s) how I can solve this? Thanks!

P.S.: When I try second possibility in Google Chrome it works perfectly.

Greetings, Joseph


回答1:


var opts = {

success: function(data)
         {
             //do everything here first before appending it,
             //including adding event bindings
         }

}

$.ajax(opts)



回答2:


Use prop instead of attr:

$('#mySelectElementOption_' + id).prop('selected', true);

or

$('#mySelect').val($('#mySelectElementOption_' + id).val());

http://jsfiddle.net/uG88d/




回答3:


Try this:
HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <select id="mySelectElement">
    <option id="oldoption" >Old option</option>
  </select>
</body>
</html>

JS:

//demo data
options = [{id:0, value:"aaa"},{id:1, value:"bbb"},{id:2, value:"ccc"}];

    for(var i = 0; i < options.length; i++) {
        var data = options[i];
        var option = $('<option id="mySelectElementOption_' + data['id'] + '" class="interactable" value="' + data['value'] + '">' + data['value'] + '</option>');
        $('#mySelectElement').append(option);
    }
//This is what you need:
        $("#mySelectElement :not([class])").attr("disabled","disabled");

Explanation:
$("#mySelectElement :not([class=interactable])") - This tells jquery to find any option element in the #mySelectElement that does not have the 'interactable' class.
Then it disables it: .attr("disabled","disabled");

Try it out: jsBin

Edit:

$("#mySelectElement .interactable:first").prop('selected', true);

Try it out



来源:https://stackoverflow.com/questions/14792014/select-option-which-were-just-appended-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!