Как найти все input jquery

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(){
    let $inputs = $("input, textarea, select", this);
});

isherwood's user avatar

isherwood

57.5k16 gold badges113 silver badges154 bronze badges

asked Oct 12, 2012 at 15:41

John Magnolia's user avatar

John MagnoliaJohn Magnolia

16.6k35 gold badges159 silver badges264 bronze badges

0

Edit: As pointed out in comments (Mario Awad & Brock Hensley), use .find to get the children

$("form").each(function(){
    $(this).find(':input') //<-- Should return all input elements in that specific form.
});

forms also have an elements collection, sometimes this differs from children such as when the form tag is in a table and is not closed.


May be :input selector is what you want

$(«form»).each(function(){
$(‘:input’, this)//<— Should return all input elements in that specific form.
});

As pointed out in docs

To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(«:input»).

You can use like below,

$("form").each(function(){
    $(this).filter(':input') //<-- Should return all input elements in that specific form.
});

Community's user avatar

answered Oct 12, 2012 at 15:43

Selvakumar Arumugam's user avatar

7

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());
    }
);

tibi's user avatar

tibi

6571 gold badge9 silver badges22 bronze badges

answered Sep 19, 2013 at 9:50

Srinivasan.S's user avatar

Srinivasan.SSrinivasan.S

3,0451 gold badge23 silver badges15 bronze badges

2

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.

answered Oct 12, 2012 at 15:44

circusdei's user avatar

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

To compound on that idea: you can use something like this to make all form elements accessible.

Data = $('form').serialize().split('&');

for(i in Data){
    Data[i] = Data[i].split('=');
    Fields[ Data[i][0] ] = [ Data[i][1],
                             $('form *[name="' + Data[i][0] + '"]').eq(0) ];
}

console.log(Fields);

// The result would be a multi-dimensional array you could loop through
Fields[Field_Name] = [Field_Value, Field_Object]

Note: This will only work with named fields as serialize() will ignore all others. Any fields with duplicate names will be ignored. You could make a multi-dimensional array if multiple fields use the same name.

TibTibs's user avatar

TibTibs

1674 silver badges11 bronze badges

answered Apr 22, 2019 at 9:25

Avnish Tiwary's user avatar

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.
});

answered Mar 9, 2014 at 23:45

Ron Sims II's user avatar

Ron Sims IIRon Sims II

5665 silver badges10 bronze badges

1

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 +=
            "nnFORM 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:nt" + 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 );
    } )
} );

answered Jul 26, 2015 at 15:43

Igor Parra's user avatar

Igor ParraIgor Parra

10.2k10 gold badges69 silver badges99 bronze badges

1

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 form_data = get_form_data();
console.log(form_data);

Function:

function get_form_data(element){
    element = element || '';
    var all_page_data = {};
    var all_forms_data_temp = {};
    if(!element){
        element = 'body';
    }

    if($(element)[0] == undefined){
        return null;
    }

    $(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;
}

answered Jun 10, 2017 at 21:10

Mohamad Hamouday's user avatar

2

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

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

answered Jun 29, 2013 at 13:17

Jan's user avatar

1

Just to add another way:

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

answered May 11, 2015 at 13:09

user3770276's user avatar

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 :)

answered Oct 15, 2019 at 18:12

Ahmed Jamal's user avatar

I used this way to get all input fields from a certain form:

$("#myForm").find("input").each(function() {
   // your stuff goes here
});

Or for the case here:

$("#myForm").find("select, textarea, input").each(function() {
   // your stuff goes here
});

answered Nov 16, 2021 at 10:31

Marco's user avatar

MarcoMarco

3,4204 gold badges23 silver badges34 bronze badges

Years later…

const formElements = Object.entries($('form').get(0).elements)
    .reduce((arr, [_, el]) => 
        el.name 
            ? Object.assign(arr, { [el.name]: el.value }) 
            : arr, 
        {}
    );

The result is a simple key:value list of all form elements with a non-empty name.

For vanilla JS, replace $('form').get(0) with simple document.querySelector('form').

answered Mar 4 at 17:12

AnrDaemon's user avatar

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[]

answered Oct 29, 2018 at 3:41

Srinath Shah's user avatar

1

all inputs:

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

all buttons

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

answered Nov 11, 2018 at 20:35

D.L.MAN's user avatar

D.L.MAND.L.MAN

97012 silver badges17 bronze badges

jquery isn’t needed.

html control elements must be one of the following:
button,fieldset,input,object,output,select,textarea

so you can use JavaScript’s native querySelectorAll

// use query selector instead
const nodes = document.querySelectorAll(
  ":where(button,fieldset,input,object,output,select,textarea)"
);
console.log({ nodes });
<div>
  <input type="text" id="name" name="name" value="bob">
</div>
<div>
  <textarea name="textarea" rows="10" cols="50">Write something here</textarea>
</div>

the above would select form control elements anywhere on the page (even outside of <form> tags). if you already have the form, and just want those elements, you could just use the elements property for the form:

const formControls = myForm.elements

answered May 1 at 18:14

bristweb's user avatar

bristwebbristweb

83714 silver badges11 bronze badges

jQuery. Как выбрать все input type text

12 мая 2016 18:05

Просмотров: 3879

Jquery selector input[type=text]

Выборка 1 способ

$('.sys input[type=text], .sys select').each(function() {...})

Выборка 2 способ

$('.sys').find('input[type=text],select').each(function() {...})

Выборка 3 способ

$('input[type=text],select', '.sys').each(function() {...})

SkeitOl

Комментарии: 1

Object of all the inputs:-

$("form#formId :input").each(function(){
    var input = $(this); // A jquery object of the input
});

or

$('#formId').submit(function() {
    // get the array of all the inputs 
    var $inputs = $('#formId :input');

    // get an associative array of the values
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });
});

This one returns the Key:Value pair —

var values = {};
$.each($('#formId').serializeArray(), function(i, field) {
    values[field.name] = field.value;
});

jQuery селекторы

Определение и применение

jQuery селектор :input выбирает все элементы <input> (пользовательское поле для ввода информации), <textarea> (поле формы для создания области многострочного ввода), <select> (раскрывающийся (выпадающий) список) и <button> (используется для размещения кнопки).

jQuery синтаксис:

$(":input")

Добавлен в версии jQuery

1.0

Селектор в CSS

Это селектор jQuery, он не является частью спецификации CSS.

Пример использования

<!DOCTYPE html>
<html>
	<head>
		<title>Использование jQuery селектора :input.</title>
		<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<script>
	$(document).ready(function(){
	   $(":input").css("border", "1px solid orange"); // выбираем все элементы <input>, <textarea>, <select> и <button> в документе
	});
		</script>
	</head>
	<body>
		<form>
			<select required> <!-- указываем, что элемент раскрывающегося списка должен быть выбран перед отправкой формы -->
				<option></option>
				<option>М</option>
				<option>Ж</option>
			</select>
			<input type = "text" placeholder = "Ваше имя"><br><br>  <!-- однострочное текстовое поле -->
			<textarea placeholder = "О себе"></textarea><br>  <!-- область многострочного ввода--> 
			<button>Отправить</button> <!-- кнопка -->
		</form>
	</body>
</html>

В этом примере с использованием селектора :input мы выбрали и стилизовали все элементы <input>, <textarea>, <select> и <button> в документе.

Результат нашего примера:

Пример использования jQuery селектора :input.

Пример использования jQuery селектора :input.
jQuery селекторы

Skip to content

The jQuery :input selector selects all the input type elements in a form. It selects every input elements including textarea, select box, and button. This can be useful when you want to select the input form elements.

jQuery :input Selector

Syntax of the Selector

The syntax of jQuery :input selector is given below.

The above syntax requires no arguments to pass to the selector. However, if you want to select only the specific input element. You have to use the tag name. Suppose, if you want to select only the select box. You have to specify the tag name select before the selector. You have to use the selector as $("select:input").

jQuery :input Selector Select All Types of Input Elements

When you want to select the form elements which are using for user inputs. You have to use this selector. It selects every element in a form including the button element. See the example below the selector selects each and every form elements.

Example

Test it Live

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<script>

$(document).ready(function(){

$( «.mydforminput :input» ).css(«background», «yellow»);

});

</script>

<form action=«#» class=«mydforminput»>

<label>Name</label>

<input type=«text» name=«name» placeholder=«Enter your name…»><br><br>

    <label>Email</label>

<input type=«email» name=«email» placeholder=«Enter your email…»><br><br>

    <label>Select Your Country</label>

    <select name=«country»>

     <option value=«»>Select option</option>

     <option value=«India»>India</option>

        <option value=«Australia»>Australia</option>

        <option value=«USA»>USA</option>

        <option value=«Germany»>Germany</option>

    </select><br><br>

    <button type=«button» name=«submit»>Submit</button>

</form>

Output

The above example showing all the selected form elements with the button element. The selector selects the input, select box, and button elements to apply the background color. It adds a ‘yellow’ color to each and every form elements to highlight them

If you have any queries regarding this tutorial post, please comment below.

Also tell me, what other methods you are using with the selector by commenting below.

References

  • jQuery Support Docs
  • W3schools Tutorial


Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Minecraft как найти сундуки
  • При разговоре по микрофону весь звук с компа идет в микрофон как исправить
  • Как исправить ушек
  • Как правильно составить диаграмму в ворде
  • Знак энтропии как найти

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии