访问递归添加字段的jquery类名

时间:2011-11-02 21:24:57

标签: jquery jquery-selectors attributes

我有一个表单,允许用户根据需要添加无限数量的额外行(文本字段输入)。我已经成功使用jQuery来创建这些额外的字段。为了这个例子,我们假设多次克隆以下内容:

<input name="datain_pline_1" id="datain_pline_1" value="" type="text" class="calc_input" maxlength="4" />
<span id="dataout_currentmult_1"></span>

在每个新实例中,数字正在递增(因此datain_pline_1变为datain_pline_2,datain_pline_3等等......我的输出范围也会相应增加。)

然后我在输入每个字段的数据上运行一些AJAX,并在相关的span标记中返回一些输出。我的代码(见下文)适用于第一个字段(#1),但我不知道如何编辑它以将.change函数应用于我的所有具有相似名称的ID ...然后如何应用相关数字也与量程输出有关。我对jQuery相对较新,但在我看来,这些东西不仅可以做到,而且相对简单......但对我来说当然不简单!非常感谢任何帮助!

$("#datain_pline_1").change(function(){

    //Get the data from the field
    var pline = $('input[name=datain_pline_1]');

    //organize the data
    var data = 'pline=' + pline.val() ;

    //start the ajax
    $.ajax({
        //this is the php file that processes the data and returns values
        url: "ajax_getPlineData.php",
        //GET method is used
        type: "GET",
        //pass the data
        data: data,
        //Do not cache the page
        cache: false,
        //success
        success: function (outputPlineData) {
            if (outputPlineData!='') {
                //success
                $('#dataout_currentmult_1').html(outputPlineData);
            } else {
                alert('Unexpected Error');
            }
        }
    });
    return true;
});

我需要帮助的地方是前两行,将其应用于所有相关的文本输入字段(并将值捕获到变量):

$("#datain_pline_1").change(function(){
var pline = $('input[name=datain_pline_1]');

和输出返回数据的底部:

$('#dataout_currentmult_1').html(outputPlineData);

2 个答案:

答案 0 :(得分:2)

好的,你需要更动态地访问它们:

// change your spans to have a class
<input name="datain_pline_1" id="datain_pline_1" value="" type="text" class="calc_input" maxlength="4" />
<span id="dataout_currentmult_1" class="calc_output"></span>

然后,将您所说的那两行改为:

// target all of the inputs (they all have the class "calc_input")
// updated to "live" per @scrappedcola's comment
$(".calc_input").live('change', function(){

//and
// target the span that is directly after the input that fired the change event
$(this).next('.calc_output').html(outputPlineData);

答案 1 :(得分:2)

对于change处理程序,如果所有输入都具有相同的类,则可以使用jquery的委托或实时函数将更改事件应用于该标识符的所有当前和未来元素。对于跨度,您可以更改span的id与datain_pline_1_SPAN类似,因此当更改事件发生时,您可以根据该id获取当前id和span。例如:

$(".calc_input").live("change", function(){
    var id = this.id;
     var span = $("#" + id + "_SPAN");
    //do rest of stuff here
});

$(document).delegate(".calc_input", "change", function(){
     var id = this.id;
     var span = $("#" + id + "_SPAN");
     //do rest of stuff here
});