Neven Grguric Neven Grguric - 3 months ago 14
jQuery Question

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.

Answer

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.