Reputation: 429
I m working on my web tech experiment myself. i have two dropdown lists quoted in a div.
<div id="A">
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
And here my javascript code:
$(document).ready(function(){
$('#A option:eq(1)').attr("selected", "selected");
});
What i expect is dropdown lists with option "2" and "7", but only got "2" but "7".oh, can i make it happen by oneline script code (instead setting two div with two tag for two dropdown) Thanks a lot for reply and help.
Upvotes: 3
Views: 3452
Reputation:
use this.
<div id="A">
<select id="s1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select id="s2">
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
----------
$(document).ready(function(){
$('#s1 option:eq(1)').attr("selected", "selected");
$('#s2 option:eq(1)').attr("selected", "selected");
});
Upvotes: 0
Reputation: 9970
$('#A > select option[value=2]).eq(0).attr('selected','selected');
$('#A > select option[value=7]).eq(1).attr('selected','selected');
Upvotes: 0
Reputation: 121998
In the first seletor it's selection only first matched element.
Use find()
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Try
$('#A>select').find('option:eq(1)').attr("selected", "selected");
Upvotes: 0
Reputation: 57095
$(document).ready(function () {
$('#A select').each(function () {
$(this).find('option:eq(1)').prop("selected", "selected");
});
});
Upvotes: 1
Reputation: 5291
$('#A').find('select option:nth-child(2)').attr("selected", "selected");
Upvotes: 2
Reputation: 13529
You should use:
$('select').find('option:eq(1)').attr("selected", "selected");
Upvotes: 0