Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if empty loop in live preview

I'm having a working live preview Script. But now i want that the field for phone and fax only are displayed, when there is an input in the form fields. But i guess there has to be an issue with the empty statement. Does anyone has an idea to fix this? Thank you very much!

$(document).ready(function() {
  updatePreview();

  $('#live-preview-form input, #live-preview-form textarea #live-preview-form select').bind('blur keyup',updatePreview);
});

function updatePreview(){
  var   contact             = $('#lp-contact'),
        company_name    = $('#lp-company_name'),
        company_extra   = $('#lp-company_extra'),
        adress          = $('#lp-adress'),
        country_code    = $('#lp-country_code'),        
        zip                 = $('#lp-zip'),     
        city            = $('#lp-city'),        
        phone           = $('#lp-phone'),
        fax                 = $('#lp-fax'),
        url                 = $('#lp-url'),
        mail            = $('#lp-mail');


        contact.text($('#contact').val());
        company_name.text($('#company_name').val());
        company_name.html($('#lp-company_name').html().replace(/\n/g,'<br />'));
        company_extra.text($('#company_extra').val());
        adress.text($('#adress').val());
        country_code.text($('#country_code').val() + '-' );
        zip.text($('#zip').val());
        city.text($('#city').val());
        if(! $('#phone')){phone.text('T ' + $('#phone').val())};
        if(! $('#fax')){fax.text('F ' + $('#fax').val())};
        url.text($('#url').val());
        mail.text($('#mail').val());
}

JS Fiddle

JS Fiddle Update #1

After a lot of trying and research i thought, maybe it works with this code: but it didn't.

 if (phone.text($('#phone').val().length) != 0){
        phone.text('T ' + $('#phone').val());
    };
like image 394
Fabrizio Cocco Avatar asked May 11 '15 05:05

Fabrizio Cocco


1 Answers

This conditions:

if (!$('#phone')) {
    phone.text('T ' + $('#phone').val())
};

should be

if (!$('#phone').length) {
    phone.text('T ' + $('#phone').val())
};

The thing is that $('#phone') is a jQuery instance object which is always a truthy value. This object is an array-like collection of the HTML elements. So correct way to check if the element is on page is to check the length of this collection. Basically, it can be demonstrated with this simple snippet:

if ({length: 0}) {
    alert('One');
}

if ({length: 0}.length) {
    alert('Two');
} 
like image 145
dfsq Avatar answered Sep 26 '22 00:09

dfsq