jquery if statement to check if there is a value of an input otherwise auto populate upon clicking link

javascript, jquery

Solution

I'd suggest the following:

var defaults = {
    USERDEFINE1 : 'LT',
    PHONENIGHT : '(111)111-1111',
    INTERNET : 'NONE',
    last_purchase : 'N/A',
    last_purchase_date : 'N/A'
};
$('#ltc_link').click(function() {
    // selects the elements
    $('#USERDEFINE1, #PHONENIGHT, #INTERNET, #last_purchase, #last_purchase_date').val(
        function(i, v) {
            // checks if the current value 'v' is an empty string,
            // if it is supplies the default value (from the object), if not
            // it sets the value to the current value
            return v == '' ? defaults[this.id] : v;
    });
});

JS Fiddle demo.

References:

- Conditional (ternary) operator.

- JavaScript Objects.

- `val()`.

Problem

I have a simple `jQuery` statement like so: ``` $(document).ready(function() { $('#ltc_link').click(function() { $('#USERDEFINE1').val( 'LT' ); $('#PHONENIGHT').val( '(111)111-1111' ); $('#INTERNET').val( 'NONE' ); $('#last_purchase').val( 'N/A' ); $('#last_purchase_date').val( 'N/A' ); }); }); ``` It populates the input fields when the link `#ltc_link` is clicked. If there is already text input into one or all of the fields than i don't want the click/link function to overwrite what the user entered. I know in javascript I can do something like so: ``` if (!third.value) { third.value = '(111)111-1111'; } if (!fourth.value) { fourth.value = 'NONE'; } if (!fifth.value) { fifth.value = 'N/A'; } if (!sixth.value) { sixth.value = 'N/A'; } ``` Need some help with the `jQuery` syntax. Thanks in advance.

Original source