选择下拉列表的bootstrap或javascript验证

时间:2017-06-02 05:30:14

标签: javascript jquery

我是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;


    });
});

1 个答案:

答案 0 :(得分:3)

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