Neven Grguric
Neven Grguric

Reputation: 45

Select option working only for first dropdown

So I have two dropdowns:

<select id="list1" name="worker" class="form-control select2" style="width: 100%;">
    <option selected="selected">Choose one</option>
    <?php foreach($names as $name) { ?>
        <option value="<?php echo $name['id'] ?>"><?php echo $name['name'] ?></option>
    <?php } ?>
</select>

<select id="list2" name="vehicle" class="form-control select2" style="width: 100%;">
    <option selected="selected">Choose one</option>
    <?php foreach($cars as $car) { ?>
        <option value="<?php echo $car['id'] ?>"><?php echo $car['name'] ?></option>
    <?php } ?>
</select>

And i have this jquery for selecting first option if there is only one:

var length1 = $('#list1> option').length;

if (length1 < 3) {
    $('select>option:eq(1)').prop('selected', true);
}

var length2 = $('#list2 > option').length;

if (length2 < 3) {
    $('select>option:eq(1)').prop('selected', true);
}

And it's only working for first one even if i put script only for second.

Upvotes: 2

Views: 72

Answers (2)

Haresh Vidja
Haresh Vidja

Reputation: 8496

First of all add class in select tag class="my_select"

$(".my_select").each(function(){
    if($(this).find('option').length==2)
    {
        $(this).val($(this).find('option:eq(1)').attr('value'));
        //or you can use below
        //$(this).find('option:eq(1)').prop('selected', true);
    }
})

Upvotes: 0

vijayP
vijayP

Reputation: 11502

Could you please try with following code:

var length1= $('#list1> option').length;

if(length1< 3) {
    $('select#list1>option:eq(1)').prop('selected', true);
}

var length2= $('#list2 > option').length;

if(length2 < 3) {
    $('select#list2>option:eq(1)').prop('selected', true);
}

Still I am not that much convinced by your if conditions which you have added above. I will recommend below code

var length1= $('#list1> option').length;

if(length1 > 1) {
    $('select#list1>option:eq(1)').prop('selected', true);
}

var length2= $('#list2 > option').length;

if(length2 > 1) {
    $('select#list2>option:eq(1)').prop('selected', true);
}

In above code we are checking if we are getting more than 1 option; and if yes then we are selecting the 2nd option i.e. option just next to Choose one option.

Upvotes: 2

Related Questions