Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determining input vs textarea in jQuery

Tags:

I wish to iterate through a form, adding each element to an area. The problem is that some of these elements are select, input, and textboxes. I know that I can use :input to solve the problem here (though, I don't really need to). The issue is that I'm having trouble determining how I could see whether or not the element is a textarea, input, select, etc. I need to do this properly because, as far as I know, jQuery("input#someinput").val() works great for inputs, but for a textarea I may need jQuery("textarea#sometexarea").text(). I'm not sure if this exists...

Anyway, here's my function so far:

function getAllFormElements(id) {

    var elements = new Array();

    jQuery(id).children().map(function(){

        for (var index = 0; index < children.length; index++) {

            elements[i] = jQuery(children[i]).val();

        }

    })

        return elements;
}
like image 442
zeboidlund Avatar asked Nov 28 '11 18:11

zeboidlund


2 Answers

val() works equally well with <input>, <select> and <textarea> elements.

If you still want to determine the actual type of elements matched by the :input selector, you can use is() with element selectors:

$(":input").each(function() {
    var $this = $(this);
    if ($this.is("input")) {
        // <input> element.
    } else if ($this.is("select")) {
        // <select> element.
    } else if ($this.is("textarea")) {
        // <textarea> element.
    }
});
like image 88
Frédéric Hamidi Avatar answered Nov 04 '22 05:11

Frédéric Hamidi


You should be able to use jQuery's .is() function - just pass a selector to .is() and it will return true if the element matches the selector. So, to see if you had a textarea, you would just check:

if($(this).is("textarea")) { doStuff(); }

http://api.jquery.com/is/

like image 28
bfink Avatar answered Nov 04 '22 07:11

bfink