Roger
Roger

Reputation: 8576

JQuery: how to know the kind of form object we are dealing with?

I am building a interactive form and loading the fields according to the answer of the user. Right now I just have two kind of objects "input radio" and "textarea". As I am getting the value of the answers via JQuery, how can I know what object I am dealing with inside the very LAST loaded fieldset?

This is what I am trying:

$.fn.getNodeName = function() { // returns the nodeName of the first matched element, or ""
    return this[0] ? this[0].nodeName : "";
};

//var $something = $('input[type=radio]:checked:last');
var $something = $('fieldset:last').parent('nth-child(2)');

//$('#news ul li:first-child').addClass('active');

alert($something.getNodeName());

But it's not working... Thanks.

Upvotes: 0

Views: 87

Answers (1)

Rob W
Rob W

Reputation: 349052

I have extended your jQuery function to also return the type, when the element is an input element:

$.fn.getNodeName = function() {
    var elem = this[0]; //Get the first element of the jQuery object
    if(!elem) return "";
    var name = elem.nodeName.toLowerCase();
    return name == "input" ? "input[type=" + elem.type + "]" : name;
};

Examples of possible return values:
textarea, input[type=text], input[type=button], ...

If you prefer other output formats, just adjust the function. Another method to specify the type is by adding an extra property to the return value, such as:

$.fn.getNodeName = function() {
    var elem = this[0]; //Get the first element of the jQuery object
    if (!elem) return "";
    var name = elem.nodeName.toLowerCase();
    if (name == "input") {
        name.type = elem.type;
    }
    return name;
};

Upvotes: 2

Related Questions