<!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>
js判断输入框的值是否为空
最新推荐文章于 2023-07-30 21:51:34 发布