Reputation: 32
e.g.I want to add 'selected' attribute at the third position. Can you explain if I can add selected attribute in append() of jquery.
for (i = 0; i < 10; i++)
{
if(i==3)
{
$('#mySelect').append($('<option>',
{
value: i,
text :i
}));
}
}
Upvotes: 0
Views: 679
Reputation: 4305
Edit: Correct the answer as per Rory McCrossan's comment(added append()
with jQuery object), and apologize for misleading.
The issue is about the if
statement, your code would only append one <option>
that is if i
equals 3.
According to the documentation, you have several options to do so...
1) Use append()
with jQuery object
for (var i = 0; i < 10; i++) {
$('#mySelect').append($('<option>', {
value: i,
text: i,
selected: i == 3 ? true : false
}))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="mySelect"></select>
2) Use appendTo()
for (var i = 0; i < 10; i++) {
$('<option>', {
value: i,
text: i,
selected: i == 3 ? true : false
}).appendTo($('#mySelect'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="mySelect"></select>
3) Use append()
with a method
for (var i = 0; i < 10; i++) {
$('#mySelect').append(CreateOption(i))
}
function CreateOption(i) {
return $('<option>', {
value: i,
text: i,
selected: i == 3 ? true : false
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="mySelect"></select>
4) Use append()
with text
for (var i = 0; i < 10; i++) {
var selected = i==3 ? ' selected=true' : ''
var option = '<option value='+ i + selected + '>' + i + '</option>'
$('#mySelect').append(option)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="mySelect"></select>
Upvotes: 1
Reputation: 337626
The issue is because of your nested if
statement, which results in only the option
with a value of 3
being appended to the select
.
To fix this you can append all the option
elements together, then set the val()
of select
to choose the specific one you want. Try this:
var html = [];
for (i = 0; i < 10; i++) {
html.push($('<option>', {
value: i,
text: i
}));
}
$('#mySelect').append(html).val(3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect"></select>
Upvotes: 2
Reputation:
How about
$('#mySelect :nth-child(3)').attr('selected', 'selected');
Upvotes: 1