jquery ottiene tutti gli elementi del form: input, textarea e select


108

Esiste un modo semplice (senza elencarli tutti separatamente) in jquery per selezionare tutti gli elementi del modulo e solo gli elementi del modulo.

Non posso usare children () ecc. Perché il modulo contiene altro HTML.

Per esempio:

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

Risposte:


179

Modifica: come sottolineato nei commenti ( Mario Awad e Brock Hensley ), usa .findper ottenere i bambini

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

i form hanno anche una raccolta di elementi, a volte questa è diversa dai figli, come quando il tag del form è in una tabella e non è chiuso.


Può essere : il selettore di input è quello che vuoi

$ ("form"). each (function () {$ (': input', this) // <- Dovrebbe restituire tutti gli elementi di input in quella forma specifica.});

Come sottolineato in docs

Per ottenere le migliori prestazioni quando si utilizza: input per selezionare gli elementi, selezionare prima gli elementi utilizzando un selettore CSS puro, quindi utilizzare .filter (": input").

Puoi usare come di seguito,

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


3
Grazie anche se dopo aver letto: api.jquery.com/input-selector le prestazioni sono un problema, posso anche elencarle. Buono a sapersi, però, è possibile
John Magnolia

8
Sono solo io o non funziona per select? EDIT: non importa, funziona con seleziona se usofind(':input')
Brock Hensley,

1
Devi usare "find" invece di "filter" qui perché "filter" non può funzionare su un singolo elemento (in questo caso l'elemento "this"). Utilizzando "filtro" non sarà possibile selezionare alcun elemento del modulo e non solo "selezionare" elementi. Grazie per @Brock Hensley per averlo sottolineato.
Mario Awad

Che ne dici di grandi forme? Ho un modulo enorme con più di 4000 elementi e questo selettore è molto lento. Nella specifica è scritto che: l'input non è ottimizzato per il browser dai CSS3, quindi non funziona per me: /. Altre idee?
Vasil Popov

@VasilPopov Quanto sopra potrebbe essere troppo lento per te. Puoi provare un paio di soluzioni, in entrambi i casi è necessario raggruppare meno elementi e selezionarli.
Selvakumar Arumugam

52

Il codice seguente aiuta a ottenere i dettagli degli elementi dal modulo specifico con l'id del modulo,

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

Il codice seguente aiuta a ottenere i dettagli degli elementi da tutti i moduli che si trovano nella pagina di caricamento,

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

Il codice seguente aiuta a ottenere i dettagli degli elementi che si trovano nella pagina di caricamento anche quando l'elemento non è posto all'interno del tag,

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

NOTA: aggiungiamo il nome del tag più elemento di cui abbiamo bisogno nell'elenco degli oggetti come di seguito,

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

Perché questo accetta tutti i valori e le opzioni di un elemento select, piuttosto che dare il valore di qualcosa che è stato selezionato o altrimenti vuoto. ?
user2906838

11

Se disponi di altri tipi, modifica il selettore:

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

Tutti gli elementi del modulo sono ora nell'array formElements.


7

Per la cronaca : il seguente frammento può aiutarti a ottenere dettagli su input, textarea, selezione, pulsante, un tag attraverso un titolo temporaneo quando li passi con il mouse.

inserisci qui la descrizione dell'immagine

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

Grande funzione! Grazie
Mohamad Hamouday

6

jQuery mantiene un riferimento all'elemento del form JS vanilla e questo contiene un riferimento a tutti gli elementi figlio del form. Puoi semplicemente prendere il riferimento e procedere in avanti:

var someForm = $('#SomeForm');

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

5

La funzione di serializzazione di JQuery rende abbastanza facile ottenere tutti gli elementi del modulo.

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

5

Questa è la mia funzione preferita e funziona come un fascino per me!

Restituisce un oggetto con tutti i dati di input, selezione e textarea.

E sta cercando di ottenere il nome degli oggetti cercando elementi name else Id else class.

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

Funzione:

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

Bello ma c'è un bug sottile in "Element_Value = jQuery ('input [name ="' + Element_Name + '"]: checks'). Val ();". Element_Name potrebbe effettivamente essere l'id o la classe del nodo, nel qual caso non troverà l'elemento.
Rafael Werlang

1
Esatto, ora l'ho risolto!
Mohamad Hamouday

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

Tutti gli elementi incluso il pulsante di invio sono ora nella variabile $ form_elements.


2
Come accedervi?
Ngenazy

3

Solo per aggiungere un altro modo:

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

1

Prova questa funzione

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

E usalo come

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

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

Godere :)


0

Prova qualcosa di simile:

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

Nota l'uso dell'input []


questo non sembra ottenere textarea o seleziona
pcarvalho

0

tutti gli ingressi:

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

tutti i pulsanti

var button = $("#formId :button")
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.