简单的jQuery验证失败

时间:2012-10-12 01:01:03

标签: javascript jquery

我想验证自己的价值,但是如果有人可以帮我解决问题,那就不行了。

function countrySelectChanged() {
    $('.sub-menu').hide();
    var selectedCountry = $('#country-select').val();
    if (selectedCountry) {
        $('#' + selectedCountry + '-select').show();
    }
}
$(document).ready(function() {     
    $('#country-select').change(countrySelectChanged);
    countrySelectChanged();

    var valid;

    $('#click').click(function(){           
        if ($("#us-select").val() =="" || $("#germany-select").val() ==""  ){
            valid = false;
        } else {
            valid = true; 
        }

        if (!(valid)) {
            $('#msg').html('NOt Passed')
        } else {
            $('#msg').html('Pass')
        }
    });    
});

这是HTML

<select id="country-select">
    <option value="none" >---</option>
    <option value="us" >US</option>
    <option value="germany">Germany</option>
</select>

<select id="us-select" class="sub-menu hide">
    <option value="none" >---</option>
    <option value="austin"  >Austin</option>
    <option value="austin2"  >Austin2</option>
</select>

<select id="germany-select" class="sub-menu hide">
    <option value="none" >---</option>
    <option value="berlin">Berlin</option>
    <option value="berlin2">Berlin2</option>
</select>

<select id="none-select" class="sub-menu hide">
    <option value="none" >---</option>
</select>

<a href="#" id="click">click me</a>
<div id="msg"></div>​

这是在线版

http://jsfiddle.net/RPWPZ/14/

3 个答案:

答案 0 :(得分:1)

工作演示 http://jsfiddle.net/SJ7Sg/ http://jsfiddle.net/95zXa/

要获取选择的选项,您需要执行此操作$("#us-select option:selected").val()

API =&gt; http://api.jquery.com/selected-selector/

休息它应符合原因:)

<强>码

function countrySelectChanged() {
    $('.sub-menu').hide();
    var selectedCountry = $('#country-select').val();
    if (selectedCountry) {
        $('#' + selectedCountry + '-select').show();
    }
}
$(document).ready(function() {

    $('#country-select').change(countrySelectChanged);
       countrySelectChanged();

    var valid;

    $('#click').click(function(){

   if ($("#us-select option:selected").val() =="none"){

      valid = false;
            }else{
      valid = true;

   }


 if (valid) {
      $('#msg').html('Success')
       return false;
  } else {

      $('#msg').html('Fail')
  }


});


});






​

答案 1 :(得分:0)

if ($('#country-select').val() =="us") {
  valid = false;
} else

答案 2 :(得分:0)

你必须改变 $("#us-select").val() =="" || $("#germany-select").val() ==""$("#us-select").val() =="none" || $("#germany-select").val() =="none"

因为您的默认值为“无” - &gt;

<select id="country-select"> <option **value="none"** >---</option> <option value="us" >US</option> <option value="germany">Germany</option> </select>