Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery auto detect if I need to use .html() or .val()

Tags:

jquery

I am writting a jquery plugin to create ajax calls designed for my app.

Inside this plugin, my ajax call looks like this (reduced to what the question need) :

    $.ajax({
        url: route,
        type: "post",
        data: inputData,
        success: function(response, textStatus, jqXHR) {
            if (outputSelector !== undefined) {

                $(outputSelector).html(response);
                // or
                $(outputSelector).val(response);

            }
        }
    });

outputSelector is a selector, defined outside the plugin. I do not know if this selector is a <div> or an <input> or even a <select>. Is there a smart way to know if I need to use val(), or html() ?

like image 228
Alain Tiemblo Avatar asked Oct 16 '12 16:10

Alain Tiemblo


3 Answers

Possibly we could check if the element has value property:

var el = $(outputSelector);
if (el[0].value !== undefined) {
    el.val(response);
} else {
    el.html(response);
}

So, somewhat like one line universal solution could be:

$(outputSelector).each(function() {
    this[this.value !== undefined ? "value" : "innerHTML"] = response;
});
like image 99
VisioN Avatar answered Sep 20 '22 12:09

VisioN


If the outputSelector is a class selector, and the elements is mixed types, you need to use .each. Although it's not good to mix div and input with same class, but if you are creating a plugin, you need to consider such case.

$(outputSelector).each(function() {
    if ('value' in this) {
        $(this).val(response);
    } else {
        $(this).html(response);
    }
});
like image 34
xdazz Avatar answered Sep 21 '22 12:09

xdazz


You can use the .is(..) method to determine which method to use.

$.ajax({
    url: route,
    type: "post",
    data: inputData,
    success: function(response, textStatus, jqXHR) {
        if (outputSelector !== undefined) {
            var $output = $(outputSelector),
                method = $output.is('input,select,textarea') ? 'val' : 'html';

            $output[method](response);
        }
    }
});
like image 26
JasonWyatt Avatar answered Sep 20 '22 12:09

JasonWyatt