【问题标题】:Check if the value is empty [duplicate]检查值是否为空[重复]
【发布时间】:2013-05-11 10:07:19
【问题描述】:

如何对此进行“检查”以检查文本字段是否为空?

jquery:

$("#AddGoogleMap").click(function () {      
    if($('#googleMapCity').val()==null) {
        alert("You need to fill out a city");
    } else {
     // do something
    }

【问题讨论】:

  • $('#googleMapCity').val()===''$('#googleMapCity').val().length===0
  • 你搜索了吗?我认为您输入问题时未列出我链接的问题或类似问题。
  • @HamZaDzCyber​​DeV: .empty() 删除内容和任何嵌套的 DOM 元素。
  • @kiddorails 对不起^^'

标签: jquery


【解决方案1】:

Working Demo

$("#AddGoogleMap").click(function () {      
    if($('#googleMapCity').val() === "") {
        alert("You need to fill out a city");
     } else {
     // do something
     }
});

【讨论】:

    【解决方案2】:
     $("#AddGoogleMap").click(function () {      
        if($('#googleMapCity').val()==='') {
        alert('You need to fill out a city');
    
         } else {
         // do something
         }
    

    【讨论】:

      【解决方案3】:

      可以这样做:

      if($.trim($('#googleMapCity').val())==="")
      

      【讨论】:

        【解决方案4】:

        首先,去掉字符串开头和结尾的空格,然后将值与空字符串进行比较,如:

        if( $.trim($('#googleMapCity').val()) === '') {
             alert("You need to fill out a city");
        } else {
         // do something
        }
        

        【讨论】:

        • +1 建议在空白区域进行修剪的最佳实践
        • 不错!谢谢!但问题是即使我在该字段中填写了一些内容,它也会触发,它是否需要成为“else”的规则?
        • @Kim:这个fiddle 可能会对您有所帮助!试一次。
        • 效果很好!非常感谢@PalashMondal
        • @Kim 很高兴它有帮助!干杯!
        【解决方案5】:
        if($('#googleMapCity').val() === "") {
         alert("You need to fill out a city");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-15
          • 2016-05-19
          • 1970-01-01
          • 2012-10-29
          • 1970-01-01
          • 2012-01-09
          • 2021-08-12
          相关资源
          最近更新 更多