1

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
  • 2
    Collins: What have you run into that vanilla jQuery won't handle? Commented Mar 1, 2011 at 23:42

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this - exactly what I need. Wondering though, what is the difference between a "jquery extension" and "jquery plugin"?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.