0

I want to show an error message but want to format the fields depending upon condition below

error message is

 ("Record is already present for no"+ $('#Number').val() + " emp1"+ $('#emp1').val() +" emp2"+ $('#emp2').val() +" out date "+ $('#outdate').val() + " indate "+ $('#indate').val());

output is :

Record is already present for no 123 emp1 AAA emp2 BBB out date 2MAY indate 5MAY

now if i'm not passing emp2 name in the textbox so value is null for emp2 how can i remove emp2 also from my above message ?

I tried with $('#emp2')==null but at the time of showing how can I delete emp2 which i have taken it into string or how can i reformat my error message ?

Neo
  • 15,491
  • 59
  • 215
  • 405

3 Answers3

2

Use the ternary operator:

"Record is already present for no "+ $('#Number').val() + ($('#emp1').val() === null ? "" : " emp1"+ $('#emp1').val()) + ($('#emp2').val() === null ? "" : " emp2"+ $('#emp2').val()) +" out date "+ $('#outdate').val() + " indate "+ $('#indate').val());
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

try like..

var text = "Record is already present for no";

if($('#Number').val()!=null)// check if null or '' comes
{
 text = text + "$('#Number').val()"
}

if($('#emp1').val()!=null)// check if null or '' comes
{
 text = text + "emp1" +"$('#emp1').val()"
}

and so on..

0

To check a Jquery Object is refered to any objects or not, I usually use .length.

if ($('#number').length == 0) {
   // no value
}

To check a object is null or undefined, use typeof

if (typeof testObject == 'undefined' || testObject == null) {
    // no value
}
long.luc
  • 1,191
  • 1
  • 10
  • 30