HTML代码:

 用户名:<input type="text" id="username">
 <p style="color:red" id="warning-message"></p>

 

JS代码:

// 获取对象
var oUsername = document.getElementById('username');
var oMsg      = document.getElementById('warning-message');

// 用户名文本框失去焦点时判断是否为空
oUsername.addEventListener('blur',function(){
    checkNull(oUsername.value);
},false)

// 利用正则去掉前后空格
function spaceTrim(val){
    return val.replace(/(^\s*)|(\s*$)/g, "");
}

// 检测为空方法
function checkNull(val){
  if (spaceTrim(val) == ''){
        oMsg.innerHTML = '用户名不能为空'
   }else{
        oMsg.innerHTML = '输入的用户名为:' + val;
   }
}

 

相关文章:

  • 2023-02-03
  • 2021-11-06
  • 2021-12-04
  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
猜你喜欢
  • 2021-05-25
  • 2021-11-27
  • 2021-10-28
  • 2021-09-09
  • 2022-12-23
  • 2022-01-05
  • 2021-06-15
相关资源
相似解决方案