-5

I am trying to null check in one input field and pop up a required message in another input field. To achieve this function i have used the below Javascript code.

$(document).on('change', '.address',function () {


  if ($(this).val() == null ) {
    $('#cutomer_id').prop('required',true);
  }
});

but this is not working as expected. but when i try the opposite if ($(this).val() != null ) its fire the required messege.

Iishfaaq Ismath
  • 77
  • 1
  • 11

1 Answers1

1

It's because null is an object, but value of element is a string

What you need is check against an empty string:

if (this.value.trim() == "")
{
  $('#cutomer_id').prop('required',true);
}

The trim() added to remove trailing spaces.

P.S. please avoid unnecessary use of jquery or any other bloatware, $(this).val() is absolutely ridiculously unnecessary

vanowm
  • 9,466
  • 2
  • 21
  • 37