Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to get form element types, names and values

I know I can get the name/value relationship by using

$(#form).serializeArray();

But is there a way to get the whole enchilada, type, name and value with one call?

like image 767
PruitIgoe Avatar asked Apr 14 '11 16:04

PruitIgoe


2 Answers

Use $("form :input")

Per the docs:

Description: Selects all input, textarea, select and button elements.

Now to your question,

there a way to get the whole enchilada, type, name and value with one call?

If you simply want to loop through the items,

$("form :input").each(function(index, elm){
  //Do something amazing...
});

But if you want to return some sort of structure, you can use .map()

var items = $("form :input").map(function(index, elm) {
    return {name: elm.name, type:elm.type, value: $(elm).val()};
});

Or if you simply want to get the elements

$("form :input").get()


Example of this on jsfiddle

like image 188
Mark Coleman Avatar answered Oct 15 '22 08:10

Mark Coleman


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 "fieldset",

$('input, select, fieldset').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
):
like image 35
Srinivasan.S Avatar answered Oct 15 '22 08:10

Srinivasan.S