Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to determine between val and HTML?

Tags:

jquery

Is there a way in jQuery to determine whether an element has a value or innerhtml (or both)? For example, if the element is input then it has a val and I can use:

$(this).val();

But if it's a div then I need to use:

$(this).html();

I need to know whether I have to use val or HTML. My piece of jQuery is:

$(".myclass").each(function(idx){
  if (this is a val based element)
    use val
  else
    use html
});
like image 628
Graham Avatar asked Dec 04 '12 16:12

Graham


4 Answers

Try this fiddle.

Html:

<div></div>
<input/>
<textarea></textarea>
<select>
    <option>foo</option>
    <option>baz</option>
</select>​

Code:

changeText("div", "baz");
changeText("input", "baz");
changeText("textarea", "baz");
changeText("select", "baz");

function changeText(selector, text) {
    var element = $(selector);
    var attr = element.attr('value');
    if (typeof attr !== 'undefined' && attr !== false) {
        element.val(text);
    } else {
        element.text(text);        
    }
}
like image 137
Anders Avatar answered Oct 09 '22 22:10

Anders


$(".myclass").each(function(k, v){
    var data = ($(v).val() ?: $(v).html());
});

Try to get data from .val(), if nothing was returned use .html().

like image 33
Gustav Westling Avatar answered Oct 09 '22 22:10

Gustav Westling


this.tagName will tell you which element type you have. jQuery object doesn't have tagName property.

like image 38
Diodeus - James MacFarlane Avatar answered Oct 09 '22 21:10

Diodeus - James MacFarlane


This should do the trick:

See DEMO

$(".myclass").each(function(idx){
    if (this.hasOwnProperty('value'))
        //use val
    else
        //use html
});
like image 1
A. Wolff Avatar answered Oct 09 '22 22:10

A. Wolff