2012-07-25 43 views
1

我有這個代碼:jQuery的,如果沒有從下拉選擇向下

$("#source_lang, #targ_lang").each(function(index, element) { 

     if ($(this +'option:selected').length== 0) { 
     //some code 
     } 
     } 

我要選擇沒有在列表中的項目時顯示錯誤消息。 這給我沒有結果(錯誤消息不顯示)。

回答

4
$("#source_lang, #targ_lang").each(function() { 
    if (this.selectedIndex === 0) { 
     //some code 
    } 
} 

或 - 不使用每個 - 你也可以檢查

if ($("#source_lang, #targ_lang").find('option:selected').length < 2) { 
    ... 
} 

(這意味着至少一個選擇沒有被選中)

+0

thnx!這非常有用。 :) – rakela 2012-07-25 10:26:27

2

使用find()

if ($(this).find('option:selected').length== 0) { 
     //some code 
} 
+0

thnx的迴應! – rakela 2012-07-25 10:26:59

0

在這裏我已經完成了上述解決方案您可以查看演示鏈接。

演示:http://codebins.com/bin/4ldqp9m

HTML

<div id="panel"> 
    <select id="sel_country" multiple="multiple" size="4" class="select"> 
    <option value="India"> 
     India 
    </option> 
    <option value="USA"> 
     USA 
    </option> 
    <option value="UK"> 
     UK 
    </option> 
    <option value="England"> 
     England 
    </option> 
    <option value="France"> 
     France 
    </option> 
    <option value="Australia"> 
     Australia 
    </option> 
    <option value="Norvey"> 
     Norvey 
    </option> 
    <option value="South Africa"> 
     South Africa 
    </option> 
    <option value="Malesiya"> 
     Malesiya 
    </option> 
    <option value="Dubai"> 
     Dubai 
    </option> 
    </select> 
    <br/> 
    <input type="button" id="btn1" name="btn1" value="Get Selected Values" /> 
    <div id="result"> 
    </div> 
</div> 

的jQuery:

$(function() { 
    $("#btn1").click(function() { 
     var seloptions = $("select#sel_country").val() || ""; 
     if (seloptions != "") { 
      $("#result").text(seloptions); 
     } else { 
      $("#result").text("You have not selected any option(s)..!"); 
     } 
    }); 
}); 

演示:http://codebins.com/bin/4ldqp9m