Ray-Von-Mice
Ray-Von-Mice

Reputation: 429

How could i set default value for mutiple dropdown using javascript(jQuery ajax whatever)?

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

Answers (6)

user2496033
user2496033

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

N8FURY
N8FURY

Reputation: 9970

$('#A > select option[value=2]).eq(0).attr('selected','selected');
$('#A > select option[value=7]).eq(1).attr('selected','selected');

Upvotes: 0

Suresh Atta
Suresh Atta

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");

Working Demo

Upvotes: 0

DEMO

$(document).ready(function () {
    $('#A select').each(function () {
        $(this).find('option:eq(1)').prop("selected", "selected");
    });
});

Upvotes: 1

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

$('#A').find('select option:nth-child(2)').attr("selected", "selected");

Upvotes: 2

Krasimir
Krasimir

Reputation: 13529

You should use:

$('select').find('option:eq(1)').attr("selected", "selected");

Upvotes: 0

Related Questions