如果文本框有值,为什么我不能显示警报?

时间:2016-05-30 11:30:14

标签: javascript jquery html

我正在尝试只在没有值的情况下运行if语句。

<script src="https://jqueryvalidation.org/files/lib/jquery-1.11.1.js"></script>
<script type="text/javascript">
    function checkNSC() {
        var confirmNSC = $("#SelectNsc");
        if (confirmNSC.length == 0) {
            alert("Please ensure all required fields are filled out")
        }
        else {
            alert("NSC has value")
        }

    }

</script>

HTML:

<input type="text" id="SelectNsc" />
<button onclick="checkNSC();" id="myButton">My Button</button>
</div>  

我试图说明值是否为0然后显示警告说(请确保填写所有字段“。否则说”NSC有值“

谢谢,

3 个答案:

答案 0 :(得分:5)

应该是,

var confirmNSC = $("#SelectNsc").val();

因为$("#SelectNsc")返回一个jquery对象,所以$("#SelectNsc").length将始终返回一个大于0的值。

<script src = "https://jqueryvalidation.org/files/lib/jquery-1.11.1.js" > < /script> 
<script type = "text/javascript" >
  $(document).ready(function() {
    $("#myButton").click(function() {
      var confirmNSC = $("#SelectNsc").val().trim();
      if (confirmNSC.length == 0) {
        alert("Please ensure all required fields are filled out")
      } else {
        alert("NSC has value")
      }
    });

  })
</script>

Fiddle

答案 1 :(得分:2)

试试这个,它工作正常

&#13;
&#13;
<script src="https://jqueryvalidation.org/files/lib/jquery-1.11.1.js"></script>
<script type="text/javascript">
    function checkNSC() {
        var confirmNSC = $("#SelectNsc");
        if (confirmNSC.val() =='') {
            alert("Please ensure all required fields are filled out")
        }
        else {
            alert("NSC has value")
        }

    }

</script>


<input type="text" id="SelectNsc" />
<button onclick="checkNSC();" id="myButton">My Button</button>
</div>  
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用此代码:

<body>
 <script src="https://jqueryvalidation.org/files/lib/jquery-1.11.1.js"></script>
<script type="text/javascript">
    function checkNSC() {
        var confirmNSC = document.getElementById("SelectNsc").value;
        if (confirmNSC.length == 0) {
            alert("Please ensure all required fields are filled out")
        }
        else {
            alert("NSC has value")
        }

    }

</script>
    <input type="text" id="SelectNsc" />
<button onclick="checkNSC();" id="myButton">My Button</button>
</body>

或者,使用此代码:

<body>
 <script src="https://jqueryvalidation.org/files/lib/jquery-1.11.1.js"></script>
<script type="text/javascript">
    function checkNSC() {
        var confirmNSC = $("#SelectNsc").val();
        if (confirmNSC.length == 0) {
            alert("Please ensure all required fields are filled out")
        }
        else {
            alert("NSC has value")
        }

    }

</script>
    <input type="text" id="SelectNsc" />
<button onclick="checkNSC();" id="myButton">My Button</button>
</body>