[jquery] jquery get all form elements: input, textarea & select

Is there an easy way (without listing them all separately) in jquery to select all form elements and only form elements.

I can't use children() etc because the form contains other HTML.

E.g:

$("form").each(function(){
    $(this, "input, textarea, select");
});

This question is related to jquery jquery-filter

The answer is


JQuery serialize function makes it pretty easy to get all form elements.

Demo: http://jsfiddle.net/55xnJ/2/

$("form").serialize(); //get all form elements at once 

//result would be like this:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

Try something like this:

<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>

<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {

  // Stop form from submitting normally
event.preventDefault();

// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='s']" ).val(),
url = $form.attr( "action" );

// Send the data using post
var posting = $.post( url, { s: term } );

// Put the results in a div
posting.done(function( data ) {
  var content = $( data ).find( "#content" );
  $( "#result" ).empty().append( content );
    });
  });
</script>

Note the use of input[]


Try this function

function fieldsValidations(element) {
    var isFilled = true;
    var fields = $("#"+element)
        .find("select, textarea, input").serializeArray();

    $.each(fields, function(i, field) {
        if (!field.value){
            isFilled = false;
            return false;
        }
    });
    return isFilled;
}

And use it as

$("#submit").click(function () {

    if(fieldsValidations('initiate')){
        $("#submit").html("<i class=\"fas fa-circle-notch fa-spin\"></i>");
    }
});

Enjoy :)


jQuery keeps a reference to the vanilla JS form element, and this contains a reference to all of the form's child elements. You could simply grab the reference and proceed forward:

var someForm = $('#SomeForm');

$.each(someForm[0].elements, function(index, elem){
    //Do something here.
});

The below code helps to get the details of elements from the specific form with the form id,

$('#formId input, #formId select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements from all the forms which are place in the loading page,

$('form input, form select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,

$('input, select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

NOTE: We add the more element tag name what we need in the object list like as below,

Example: to get name of attribute "textarea",

$('input, select, textarea').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

Just to add another way:

$('form[name=' + formName + ']').find(':input')

This is my favorite function and it works like a charm for me!

It returns an object with all for input, select and textarea data.

And it's trying to getting objects name by look for elements name else Id else class.

var All_Data = Get_All_Forms_Data();
console.log(All_Data);

Function:

function Get_All_Forms_Data(Element)
{
    Element = Element || '';
    var All_Page_Data = {};
    var All_Forms_Data_Temp = {};
    if(!Element)
    {
        Element = 'body';
    }

    $(Element).find('input,select,textarea').each(function(i){
        All_Forms_Data_Temp[i] = $(this);
    });

    $.each(All_Forms_Data_Temp,function(){
        var input = $(this);
        var Element_Name;
        var Element_Value;

        if((input.attr('type') == 'submit') || (input.attr('type') == 'button'))
        {
            return true;
        }

        if((input.attr('name') !== undefined) && (input.attr('name') != ''))
        {
            Element_Name = input.attr('name').trim();
        }
        else if((input.attr('id') !== undefined) && (input.attr('id') != ''))
        {
            Element_Name = input.attr('id').trim();
        }
        else if((input.attr('class') !== undefined) && (input.attr('class') != ''))
        {
            Element_Name = input.attr('class').trim();
        }

        if(input.val() !== undefined)
        {
            if(input.attr('type') == 'checkbox')
            {
                Element_Value = input.parent().find('input[name="'+Element_Name+'"]:checked').val();
            }
            else if((input.attr('type') == 'radio'))
            {
                Element_Value = $('input[name="'+Element_Name+'"]:checked',Element).val();
            }
            else
            {
                Element_Value = input.val();
            }
        }
        else if(input.text() != undefined)
        {
            Element_Value = input.text();
        }

        if(Element_Value === undefined)
        {
            Element_Value = '';
        }

        if(Element_Name !== undefined)
        {
            var Element_Array = new Array();
            if(Element_Name.indexOf(' ') !== -1)
            {
                Element_Array = Element_Name.split(/(\s+)/);
            }
            else
            {
                Element_Array.push(Element_Name);
            }

            $.each(Element_Array,function(index, Name)
            {
                Name = Name.trim();
                if(Name != '')
                {
                    All_Page_Data[Name] = Element_Value;
                }
            });
        }
    });
    return All_Page_Data;
}

If you have additional types, edit the selector:

var formElements = new Array();
$("form :input").each(function(){
    formElements.push($(this));
});

All form elements are now in the array formElements.


all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

var $form_elements = $("#form_id").find(":input");

All the elements including the submit-button are now in the variable $form_elements.


For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.

enter image description here

$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
    var $tag = $( this );
    var $form = $tag.closest( 'form' );
    var title = this.title;
    var id = this.id;
    var name = this.name;
    var value = this.value;
    var type = this.type;
    var cls = this.className;
    var tagName = this.tagName;
    var options = [];
    var hidden = [];
    var formDetails = '';

    if ( $form.length ) {
        $form.find( ':input[type="hidden"]' ).each( function( index, el ) {
            hidden.push( "\t" + el.name + ' = ' + el.value );
        } );

        var formName = $form.prop( 'name' );
        var formTitle = $form.prop( 'title' );
        var formId = $form.prop( 'id' );
        var formClass = $form.prop( 'class' );

        formDetails +=
            "\n\nFORM NAME: " + formName +
            "\nFORM TITLE: " + formTitle +
            "\nFORM ID: " + formId +
            "\nFORM CLASS: " + formClass +
            "\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
    }

    var tempTitle =
        "TAG: " + tagName +
        "\nTITLE: " + title +
        "\nID: " + id +
        "\nCLASS: " + cls;

    if ( 'SELECT' === tagName ) {
        $tag.find( 'option' ).each( function( index, el ) {
            options.push( el.value );
        } );

        tempTitle +=
            "\nNAME: " + name +
            "\nVALUE: " + value +
            "\nTYPE: " + type +
            "\nSELECT OPTIONS:\n\t" + options;

    } else if ( 'A' === tagName ) {
        tempTitle +=
            "\nHTML: " + $tag.html();

    } else {
        tempTitle +=
            "\nNAME: " + name +
            "\nVALUE: " + value +
            "\nTYPE: " + type;
    }

    tempTitle += formDetails;

    $tag.prop( 'title', tempTitle );
    $tag.on( 'mouseout', function() {
        $tag.prop( 'title', title );
    } )
} );