使用 jQuery 检查值是否为 null

Luc*_*ier 3 jquery

我试图检查变量的值是否为空,但它不起作用。我还必须停止脚本并且不要插入行

网页

<input type="text" name="for_intitule" id="form_intitule">
Run Code Online (Sandbox Code Playgroud)

jQuery

var form_intitule = $('input[name=form_intitule]').val();

if(form_intitule == null){
  alert('fill the blank');
  return false;
}
Run Code Online (Sandbox Code Playgroud)

更新 :

$('#insertForm').on('click', function(){
  var form_intitule = $('input[name=form_intitule]').val();

  if($('input[name=form_intitule]').val().trim().length == 0){
    alert('fill the blank');
  }
  $.ajax({
    type: "GET",
    url: "lib/function.php?insertForm="+insertForm+"&form_intitule="+form_intitule,
    dataType : "html",
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
    },
    success:function(data){
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

Pra*_*man 5

总是.val()返回一个string. 您可以使用以下命令检查字符串是否为空:

.val().trim().length == 0
Run Code Online (Sandbox Code Playgroud)

所以你的完整条件将是:

var form_intitule = $('input[name=form_intitule]').val().trim();

if (form_intitule.length == 0) {
  alert('fill the blank');
  return false;
}
Run Code Online (Sandbox Code Playgroud)