2016-08-11 39 views
2
工作選擇選項

所以我有兩個下拉列表:只對第一個下拉

<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> 

,我有這個jQuery選擇第一個選項,如果只有一條:

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

而且只有工作第一個,即使我只爲第二個腳本。

回答

2

請您用下面的代碼試試:

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

不過我沒有那麼多的,你在上面添加您的if條件信服。我會推薦下面的代碼

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

在,如果我們越來越超過1 option我們正在檢查上面的代碼;如果是,那麼我們選擇第二個選項,即Choose one選項旁邊的選項。

+0

這works..thanks! :) –

+0

謝謝@NevenGrguric ...':)'! – vijayP

0

首先添加類中選擇標記類= 「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); 
    } 
}) 
相關問題