3

I'm trying to check if the value of my variable is null but it does not work. And i also have to stop script and don't insert the row

Html

<input type="text" name="for_intitule" id="form_intitule">

Jquery

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

if(form_intitule == null){
  alert('fill the blank');
  return false;
}

UPDATE :

$('#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){
    }
  });
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Lucas Frugier
  • 277
  • 1
  • 4
  • 12

2 Answers2

5

The .val() always returns a string. You can check if the string is empty using:

.val().trim().length == 0

So your full condition will be:

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

if (form_intitule.length == 0) {
  alert('fill the blank');
  return false;
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

I would suggest a safer method

var formElement = $('input[name=form_intitule]');
if ($(formElement).length == 0 || $(formElement).val().trim().length == 0) {
   console.log("element does not exist OR value is empty");
}
Devaffair
  • 182
  • 14