如何仅在填写所有表单字段时显示结果?

时间:2014-06-02 22:30:50

标签: javascript jquery forms calculator

这是我的代码:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function(){
      $(".input").bind("change keyup", function(){
            var val1 = +$(".value1").val();
            var val2 = +$(".value2").val();
            var val3 = +$(".value3").val();
            var val4 = +$(".value4").val();
            $("#result").val(val1+val2+val3+val4);
     });
  });
  </script>
</head>
<body>
  <select class="input value1">
    <option value="">Choose</option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <select class="input value2">
    <option value="">Choose</option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <select class="input value3">
    <option value="">Choose</option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <input type="text" class="input value4">
  <input type="text" disabled="disabled" id="result">
</body>
</html>

我想仅在填写或选择所有字段时显示结果。此外,在禁用的文本字段中,我想在未填充某些字段时打印“必须检查每个字段”之类的消息。如何修改此代码才能实现此目的?

1 个答案:

答案 0 :(得分:0)

就这样做:

$(document).ready(function(){
  $(".input").bind("change keyup", function(){
        var val1 = +$(".value1").val();
        var val2 = +$(".value2").val();
        var val3 = +$(".value3").val();
        var val4 = +$(".value4").val();

        if(parseFloat(val1) > 0 && parseFloat(val2) > 0 && parseFloat(val3) > 0 && parseFloat(val4) > 0) {
           $("#result").val(val1+val2+val3+val4);
        }
        else {
           $("#result").val('You must check every field');
        }              
   });
});