jquery 获取所有表单元素:输入、文本区域和选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12862601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:04:40  来源:igfitidea点击:

jquery get all form elements: input, textarea & select

jqueryjquery-filter

提问by John Magnolia

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

在 jquery 中是否有一种简单的方法(不单独列出它们)来选择所有表单元素并且只选择表单元素。

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

我不能使用 children() 等,因为表单包含其他 HTML。

E.g:

例如:

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

回答by Selvakumar Arumugam

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

编辑:正如评论中指出的(马里奥阿瓦德布洛克亨斯利),.find用来让孩子们

$("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.

表单也有一个元素集合,有时这与子元素不同,例如当表单标签在表格中并且未关闭时。

var summary = [];
$('form').each(function () {
    summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');
    summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');
});

$('#results').html(summary.join('<br />'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="A" style="display: none;">
    <input type="text" />
    <button>Submit</button>
</form>
<form id="B" style="display: none;">
    <select><option>A</option></select>
    <button>Submit</button>
</form>

<table bgcolor="white" cellpadding="12" border="1" style="display: none;">
<tr><td colspan="2"><center><h1><i><b>Login
Area</b></i></h1></center></td></tr>
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input
name="id" type="text"></td></tr>
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"
type="password"></td></tr>
<tr><td><center><input type="button" value="Login"
onClick="pasuser(this.form)"></center></td><td><center><br /><input
type="Reset"></form></td></tr></table></center>
<div id="results"></div>



May be :inputselector is what you want

可能是:input选择器是你想要的

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

$("form").each(function(){ $(':input', this)//<-- 应该返回该特定表单中的所有输入元素。});

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

正如文档中指出的那样

为了在使用 :input 选择元素时获得最佳性能,首先使用纯 CSS 选择器选择元素,然后使用 .filter(":input")。

你可以像下面这样使用,

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

回答by Srinivasan.S

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

下面的代码有助于从具有表单 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());
    }
);

回答by circusdei

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.

所有表单元素现在都在数组 formElements 中。

回答by Igor Parra

For the record: The following snippet can help you to get details about input, textarea, select, button, atags 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 );
    } )
} );

回答by Ron Sims II

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:

jQuery 保留对 vanilla JS 表单元素的引用,其中包含对所有表单子元素的引用。您可以简单地获取参考并继续前进:

var someForm = $('#SomeForm');

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

回答by Mohamad Hamouday

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.

它试图通过查找元素名称 else Id else 类来获取对象名称。

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

回答by Jan

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

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

包括提交按钮在内的所有元素现在都在变量 $form_elements 中。

回答by Avnish alok

JQuery serializefunctionmakes it pretty easy to get all form elements.

JQuery序列化函数使得获取所有表单元素变得非常容易。

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

演示: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

回答by user3770276

Just to add another way:

只是添加另一种方式:

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

回答by Srinath Shah

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

注意 input[] 的使用