Friday, January 25, 2019

jquery - Display a link in javascript if var is not empty. checking var endefined not working




I need to display a link in sweetalert html only if the var is not empty. Here is the code:



$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');

var address = $this.data('address');
var report = $this.data('report');
swal({
title: name,
html:
"Gender: " + gender +"
" +
"Age: " + age +"
" +
"Country: " + country +"
" +
"Address: " + address +"
" +
(report!=undefined?'View Report':''),

});
});


I need the report link to be displayed only if var report is not empty. Here is the code pen:
https://codepen.io/pamela123/pen/GOJZgo



I tried



if(report){

report = $this.data('report');
}


report is "undefined". report!=undefined is not working.



But how not to display the report link inside the html if report is empty ??



I know it is a simple javascript question, but being a newbie i could not get further.


Answer




Put the data in a separate variable.



Then check if report is not undefined. If not, add it to the variable.



$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');

var country = $this.data('country');
var address = $this.data('address');
var report = $this.data('report');

var htmlData = "Gender: " + gender + "
" +
"Age: " + age + "
" +
"Country: " + country + "
" +
"Address: " + address + "
";
if( report !== undefined && report != "" ) {
htmlData += 'View Report'

}
swal({
title: name,
html: htmlData
});
});

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...