如何使用jQuery检查输入字段是否为空?

时间:2019-06-16 18:05:27

标签: jquery

有两个字段来计算勾股数。在将条件指令添加到空白字段之前,代码运行良好。

如果这些字段为空,则会显示该消息。

HTML:

<p>Lengte van lijn a:</p><input id="a" type="text">
<p>Lengte van lijn b:</p><input id="b" type="text">
<button class="btn" id="PythaCal">REKENEN</button>
<P id="resPytha"></P>

JQ:

function berekenLijnC() {
    var a;
    var b;
    var c;
    a = parseFloat($("#a").val());
    b = parseFloat($("#b").val());

    if (a == "" && b == "") {
        $('#resPytha').html('u vergat alle in te vullen');
    } else if (a == "" || b == "") {
        $('#resPytha').html('u vergat iets  in te vullen');
    } else {
        c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        $("#resPytha").html("lijn C is dan " + c + " cm lang");
    };
 };
 $("#PythaCal").click(berekenLijnC);

1 个答案:

答案 0 :(得分:0)

由于变量abparseFloat(),因此只要字段为空或不是数字,此变量就返回NaN。因此,在这种情况下,请检查字段是否包含数字。将if支票更改为if (isNaN(a) || isNaN(b)) {

function berekenLijnC() {
    var a;
    var b;
    var c;
    a = $("#a").val();
    b = $("#b").val();



    // Check if both of the field are empty
    if (a === "" && b === "") {
        $('#resPytha').html('Beide velden zijn leeg..');
    } else if(a === "" || b === ""){
        // Check is one of the field is empty
        $('#resPytha').html('Een van de velden is leeg..');
    } else {
        c = Math.sqrt(Math.pow(parseFloat(a), 2) + Math.pow(parseFloat(b), 2));
        $("#resPytha").html("lijn C is dan " + c + " cm lang");

    };

};
$("#PythaCal").click(berekenLijnC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Lengte van lijn a:</p><input id="a" type="text">
<p>Lengte van lijn b:</p><input id="b" type="text">
<button class="btn" id="PythaCal">REKENEN</button>

<P id="resPytha"></P>