js判断输入框的值是否为空

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>JS判断输入框的值是否为空</title>
</head>

<body>
<input type="text" id="txt"/>
<input type="button" value="检测" id="btn">

<script>
    var oTxt = document.getElementById('txt');
    var oBtn = document.getElementById('btn');

    function isnull(val) {
        var str = val.replace(/(^\s*)|(\s*$)/g, '');//把val首尾的空格去掉。

        if (str == '' || str == undefined || str == null) {//输入框中输入空格也为空
            //return true;
            console.log('空');
            console.log("str.length====" + str.length);
        } else {
            //return false;
            console.log('非空');//输入框中输入null、undefined也为非空
            console.log("str.length====" + str.length);
        }
    }

    oBtn.onclick = function () {
        isnull(oTxt.value);
    };

    /*------------------------------------------------------------------*/
    /*
     //str.length=0与str=""、str=''等价
     var a="";
     var b='';
     console.log(a==b);//true
     console.log(a.length);//0
     */


    /*判断字符串是否为空*/
    function strIsNull(str) {
        if (str.length == 0) {
            console.log('空');
        }
    }

    /*用户没输入或输入了空格*/
    function strIsEmpty(str) {
        if (str.replace(/(^s*)|(s*$)/g, "").length == 0) {
            console.log('请输入内容');
        }
    }

    /*判断输入字符串是否为空或者全部都是空格*/
    function isBlank(str) {
        if (str == "") {
            return true;
        }
        var regu = "^[ ]+$";
        var re = new RegExp(regu);
        return re.test(str);
    }

    //exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。
    function isNull(exp) {
        if (exp == null) {
            console.log("is null");
        }
    }

    //同时判断 null 和 undefined 时可使用本法。
    function isNullOrUndefined(exp) {
        if (!exp) {
            console.log("is null");
        }
    }

    /*同时判断 null、undefined、数字零、false 时可使用本法*/
    /*如果 exp 为 undefined,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。*/
    function isNullOrUndefinedOr0Orfalse(exp) {
        if (typeof(exp) == "null") {
            console.log("is null");
        }
    }


</script>
</body>
</html>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值