2017-06-02 71 views
0

我是Bootstrap或Javascript的新手,我面臨下拉選擇驗證的問題。我已經從數據庫中動態地檢索了列表項,並且想要爲它設置驗證,它應該被選擇爲強制的,所以你能否幫我做到這一點?提前致謝!!bootstrap或javascript驗證選擇下拉列表

$(function() { 
    $("#save").click(function() { 
     var optionTypeId = $("#optionTypeId"); 

     if (optionTypeId.val() == '-') { 
      //If the "Please Select" option is selected display error. 
      alert("Please select an option!"); 
      return false; 
     }   
      return true; 


    }); 
}); 
+0

你能告訴你的下拉菜單中的HTML代碼 – prasanth

+3

什麼是與當前的代碼的問題嗎? – jkris

回答

2

$(document).ready(function() { 
 
    var select = $('#test_select'), 
 
     save_btn = $('#save_btn'); 
 

 
    save_btn.on('click',function(e){ 
 
     if(select.length){ 
 
      if(select.val() === '') alert('select smth'); 
 
      else console.log('select val ='+select.val()); 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<select id="test_select"> 
 
    <option value="">Please select</option> 
 
    <option value="saab">Saab</option> 
 
    <option value="opel">Opel</option> 
 
    <option value="audi">Audi</option> 
 
</select> 
 
    
 
<button id="save_btn">SAVE</button> 
 
    
 
</body> 
 
</html>