I am looking for a jquery plugin that will check the type of element and set its value wither its via html() or val() or text() depending on the element. Is such available? Would be great to have a common plugin to set the value of a html element.
1 Answer
I don't think you'd need a plugin for this, but you could write a quick jQuery extension:
$.fn.set_val = function(value) {
switch ( this[0].nodeName.toLowerCase() ) {
case 'input':
$(this[0]).val(value);
break;
default:
$(this[0]).html(value);
break;
}
};
Then you could call it like this:
<input type="text" name="foo" id="foo" value="" />
<div id="bar"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').set_val('hello');
$('#bar').set_val('goodbye');
});
</script>
You could add more conditions for different HTML elements to the switch statement as needed. http://jsfiddle.net/hans/4T3x5/
2 Comments
amateur
Thanks for this - exactly what I need. Wondering though, what is the difference between a "jquery extension" and "jquery plugin"?
Jon Gauthier
The way I see it, jQuery plugins are usually extensions as well. Plugins are just "pluggable" — meaning you can download a plugin file, add it to any HTML, and everything suddenly works. Extensions are just pieces of code that might be specific to a particular project and not easily portable to other projects.