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!
PS: When I try second possibility in Google Chrome it works perfectly.
Greetings, Joseph
var opts = {
success: function(data)
{
//do everything here first before appending it,
//including adding event bindings
}
}
$.ajax(opts)
Use prop
instead of attr
:
$('#mySelectElementOption_' + id).prop('selected', true);
or
$('#mySelect').val($('#mySelectElementOption_' + id).val());
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.