JQuery:获取所有Input元素的ID、Value

JQuery: get ID,Value of all Input elements

本文关键字:ID Value 元素 Input 获取 JQuery      更新时间:2023-09-26

我正在尝试获取'page-templet1'上每个输入元素的所有ID和值我没有成功

function Temp1() {          
var input = [];
$('page-templete1 input[name][id][value]').each(function(){

input.push(this);
cc=$(this).attr('id'));
 alert(cc); // trying to get one at time (not working)});
alert(input[0].id); // not working
alert(input[0].attr('id')); // not working
});
alert(input[0].id); // not working
alert(input[0].attr('id')); // not working 

}

如何获取页面中所有Input元素的ID和值,并在以后访问其中一个注意:我确实知道输入元素的ID或有多少。有一篇旧帖子谈到了类似的问题,但没有解决我的问题

根据您的"页面"是否为id,您可能需要在选择器之前加上句点或散列:

var results = [];
$('#page-templete1 input').each(function(){
    results.push({
        id: this.id,
        value: this.value
    });
});

尝试以下代码:

  $(function(){
    $("input").each(function(){
        alert($(this).attr('id'))
    })
    })
var inputs = [];
$('page-templete1 input').each(function(){
    var id=$(this).attr('id'),
        val = $(this).val();
    alert("id: " + id + " with value: "+ val);
    inputs.push({id:id, value:val});
});

将数组分配给变量var inputs = [];,然后尝试通过引用未定义的变量input.push(this);读取数组(使用input而不是inputs)。

尝试使用jquery输入选择器并对其进行迭代。

试试这个

        $(function(){
             jQuery( "#pageTemplate :input" ).each(function(){
                var id = this.id;       // for id
                var value = this.value; // for value
            })
        })

注意:您必须指定您的page-templet1是id还是类

serializeArray将帮助您试试这个:

var array = jQuery('your input selector').serializeArray();

结果将是

array{{name="", value=""})

要访问,请尝试此

var array = jQuery('input').serializeArray();
array.each(function(obj){
    //do what with your object
});