2

So, I have the following js markup:

jQuery(document).on( 'click', '.rhpcon', function(e) {  
    var rhp_name = jQuery(this).find('.rhi').data("name");

    var my_html = '<div class="rhfi">'+ rhp_name +'</div>'; 
        my_html += '<div class="something">Show something else</div>';                          
    jQuery('.rh_pop').html(my_html);                        
});

As you can see, the rhp_name variable is used in the hardcoded html.

However, there are scenarios where data-name does not exist (ie, no rhp_name variable).

In a scenario where there is no rhp_name variable, I don't want the first my_html line to be used.

How do I check if the var is empty and so on?

Thanks!

3 Answers 3

9
if(typeof rhp_name !== 'undefined' && rhp_name != ''){

should do the trick

Sign up to request clarification or add additional context in comments.

Comments

4
if (rhp_name.length > 0) 
    console.log("rhp_name exists");

1 Comment

if the variable rhp_name is undefined, calling length on it will cause an error.
1

According to the documentation if the attribute is not set .data returns an empty string. So then you could try:

jQuery(document).on( 'click', '.rhpcon', function(e) {  
    var rhp_name = jQuery(this).find('.rhi').data("name");
    if(rhp_name!=""){
         var my_html = '<div class="rhfi">'+ rhp_name +'</div>';
         my_html += '<div class="something">Show something else</div>'; 
         jQuery('.rh_pop').html(my_html);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.