使用jQuery获取动态创建的文本框的值 [英] getting the value of dynamically created textbox using jquery

查看:77
本文介绍了使用jQuery获取动态创建的文本框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难获得动态附加的文本框的值.我正在使用$.each函数根据其idid中的索引来迭代所有文本框.

I'm having a hard time with getting the value of my dynamically appended textboxes. I'm using the $.each function to iterate all of the textboxes according to its id and index within the id.

<input type="text"  id="student_grde_G[1]" >
<input type="text"  id="student_grde_G[2]" >
<input type="text"  id="student_grde_G[3]" >

<input type="button" id="save_grade_button" class="button" value="Save Grades">

jQuery:

$('#save_grade_button').click(function (){
    $.each($('#student_grde_G[]'), function(i, item) {
        var grade =  $('#student_grde_G['+i+']').val();
        alert(grade);
    });
});

这不起作用.谁能告诉我该如何解决?

This doesn't work. Can anyone tell me how I can fix this?

推荐答案

您为每个选项使用的选择与您的想法不符. []用于匹配元素的属性.

The selection you are using for the each does not match what you think. [] is meant for matching attributes of elements.

例如'$("img [alt]")'选择具有alt属性的所有img标签,而$("img [alt = foo]")'选择alt属性值为foo的所有img标签.

E.g. '$("img[alt]")' selects all img tags with an alt attribute and $("img[alt=foo]")' selects all img tags where the value of the alt attribute is foo.

我建议使用一个类,而不是将输入元素更改为

I'd suggest to use a class instead change the input elements to

<input type="text" class="grades" id="student_grde_G[2]" >

,然后将jQuery更改为

and then change the jQuery to

$('#save_grade_button').click(function (){
    $.each($('grades'), function() {
        var grade =  $(this).val();
        alert(grade);
    });
});

您使用的i会忽略最后一个元素.索引(i)基于零,因此i的第一个值为0(在您的示例中为空),最后一个为元素计数减去一个,导致最后一个元素从未被选择.

the use of i you have ignores the last element. The index (i) is zero based so the first value of i is 0 (which in your example will select nothing) and the last is the count of elements minus one resulting in the last element never being selected.

但是,由于在提供给每个元素的函数中,当前元素都可以作为this来访问,因此,如果您对函数进行了上述更改,则无需担心任何一举成名"错误

However since the current element is accessible as this in the function provided to each, you don't need to worry about any "off by one" errors, if you make the above change to the function

这篇关于使用jQuery获取动态创建的文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆