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() ?
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;
});
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);
}
});
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With