jQuery - How do I simplify code that performs similar, but slightly different functions?

65 Views Asked by At

I have several lines of code that perform similar functions (they take the values from inputs and appends a line of code). Is there a way that I could simplify these?

    //======Name
        var name = $('input[name=Name]').val();
        if (name){
        $('.results').append('<div class="item">' + '<p>Your name is ' + name + '.</p>' + '</div>');}
//======Age
        var age = $('input[name=YourAge]:checked').val();
        if (age){
        $('.results').append('<div class="item">' + '<p>Your age is ' + age + '.</p>' + '</div>');}
//======Occupation
        var occupation = $('input[name=Occupation]').val();
        if(occupation){
        $('.results').append('<div class="item">' + '<p>Your occupation is ' + occupation + '.</p>' + '</div>');}
2

There are 2 best solutions below

2
On BEST ANSWER

Look at what's the same in each piece, and what's different. Turn the similar parts into the body of a function, and make the different parts the parameters to the function:

function appendResult(selector, label) {
    var result = $(selector).val();
    if (result){
        $('.results').append('<div class="item">' + '<p>Your ' label ' is ' + result + '.</p>' + '</div>');
    } 
}

Then, use it like:

appendResult('input[name=Name]', 'name');

appendResult('input[name=YourAge]:checked', 'age');

appendResult('input[name=Occupation]', 'occupation');

Notice how each piece of code only differs by the selector used, and the "label" printed to describe the item. Those two pieces become the parameters, and after you rename some variables, you'll have a generalized function you can use.

0
On

You can just create a function.

function checkExists(field) {
            if(field) {
                $('.results').append('<div class="item">' + '<p>Your ' + field.attr('name').toLowerCase() + ' is ' + field + '.</p>' + '</div>');
            }
        }

I added .toLowerCase so it grammatically makes sense. You will, of course, need to call the function and pass the field as an argument.

checkExists($('input[name=Name]'));