繁体   English   中英

如何在jQuery中获取动态创建的文本框的动态ID

[英]how to get dynamic id of dynamically created textbox in jquery

我想通过文本框ID执行keyup事件,并且所有文本框都是通过onclick按钮事件动态创建的。 为此,我必须使20键功能。 如果我使用20键功能,那么我的代码将变得冗长和复杂。 而不是我想对所有文本框使用通用功能。 有人可以建议我怎么做..谢谢

这是我正在解决的问题:

<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
    </div>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script>
$(document).ready(function() {
    var counter = 2;
    $(".add_field_button").click(function() {
        if (counter > 10) {
            alert("Only 10 textboxes allow");
            return false;
        }

        var newTextBoxDiv = $(document.createElement('div'))
            .attr("id", 'TextBoxDiv' + counter);

        newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
            '<input type="text" name="textbox' + counter +
            '" id="firsttextbox' + counter + '" value="" >&nbsp;&nbsp;<input type="text" name="textbox' + counter +
            '" id="secondtextbox' + counter + '" value="" >  <a href="#" id="remove_field">Remove</a><input type="text" id="box' + counter + '" value="">sum</div>');
        newTextBoxDiv.appendTo("#TextBoxesGroup");

        counter++;

    });

    function check(a, b) {
        var first = a;
        var second = b;
        var temp = temp;
        var novalue = "";
        result = parseInt(first) + parseInt(second);
        if (!isNaN(result)) {
            return result;
        } else {
            return novalue;
        }
    }


    $(this).on("keyup", "#firsttextbox2", function(e) {
        e.preventDefault();
        var a = document.getElementById('firsttextbox2').value;
        var b = document.getElementById('secondtextbox2').value;
        var number = 2;
        result = check(a, b);
        document.getElementById('box2').value = result;

    });

    $(this).on("keyup", "#firsttextbox3", function(e) {
        var number = 3;
        e.preventDefault();
        var a = document.getElementById('firsttextbox3').value;
        var b = document.getElementById('secondtextbox3').value;
        result = check(a, b);
        document.getElementById('box3').value = result;
    });

    $(this).on("keyup", "#firsttextbox4", function(e) {
        var number = 4;
        e.preventDefault();
        var a = document.getElementById('firsttextbox4').value;
        var b = document.getElementById('secondtextbox4').value;
        result = check(a, b);
        final = document.getElementById('box4').value = result;
    });

    $(this).on("keyup", "#secondtextbox2", function(e) {
        e.preventDefault();
        var a = document.getElementById('firsttextbox2').value;
        var b = document.getElementById('secondtextbox2').value;

        result = check(a, b);
        document.getElementById('box2').value = result;

    });

    $(this).on("keyup", "#secondtextbox3", function(e) {
        e.preventDefault();
        var a = document.getElementById('firsttextbox3').value;
        var b = document.getElementById('secondtextbox3').value;
        result = check(a, b);

        document.getElementById('box3').value = result;
    });

    $(this).on("keyup", "#secondtextbox4", function(e) {
        e.preventDefault();
        var a = document.getElementById('firsttextbox4').value;
        var b = document.getElementById('secondtextbox4').value;
        result = check(a, b);

        document.getElementById('box4').value = result;
    });


    $(this).on("click", "#remove_field", function(e) { //user click on remove text
        e.preventDefault();
        $(this).parent('#target').remove();
        counter--;

    });


});
</script>

请参见下面的代码片段,以了解如何使此实现更具模块化和可用性。 诀窍在于思考:我想做什么? 我希望能够添加多个输入并添加其值,然后将结果打印在另一个输入中。

归结为使用classes -因为我们将在每一行中使用相同的东西。 然后应用适用于所有类的内容。 没有任何ID! 您甚至可以使用包含要保存的值的输入的name属性。 在发布时在该属性中使用[]甚至可以将您传递回漂亮的数组!

我知道这看起来很艰巨,但是删除我的注释后,行数将大大减少,并且这种代码几乎可以无限扩展和重用。

但是,看看它,它的工作原理很简单,而且最重要的是-DRY(一旦don't repeat yourself 0,请重新评估,因为应该有更好的方法!)!

更新资料

您还可以使用<ol>作为包装器,然后每次在其中添加<li> ,这样您就可以自动对前端的盒子进行计数,而无需您的任何努力! 实际上,那太好了,以至于我更改了实现。

 var add = $('#add_boxes'); var all = $('#boxes'); var amountOfInputs = 2; var maximumBoxes = 10; add.click(function(event){ // create a limit if($(".box").length >= maximumBoxes){ alert("You cannot have more than 10 boxes!"); return; } var listItem = $('<li class="box"></li>'); // we will add 2 boxes here, but we can modify this in the amountOfBoxes value for(var i = 0; i < amountOfInputs; i++){ listItem.append('<input type="text" class="input" />'); } listItem.append('<input type="text" class="output" name="value" />'); // Lets add a link to remove this group as well, with a removeGroup class listItem.append('<input type="button" value="Remove" class="removeGroup" />') listItem.appendTo(all); }); // This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly. $(document).on("keyup", "input.input", function(event){ // Get the group var group = $(this).parent(); // Get the children (all that arent the .output input) var children = group.children("input:not(.output)"); // Get the input where you want to print the output var output = group.children(".output"); // Set a value var value = 0; // Here we will run through every input and add its value children.each(function(){ // Add the value of every box. If parseInt fails, add 0. value += parseInt(this.value) || 0; }); // Print the output value output.val(value); }); // Lets implement your remove field option by removing the groups parent div on click $(document).on("click", ".removeGroup", function(event){ event.preventDefault(); $(this).parent(".box").remove(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <ol id="boxes"> </ol> <input type="button" value="Add a row" id="add_boxes" /> 

您可以使用以下简单功能来定位所有当前或将来的文本框,无论其数量是多少:

 $(document).on("keyup", "input[type=text]", function(){ var $textbox = $(this); console.log($textbox.val()); }) $("button").click(function(){ $("#container").append('<input type="text" /><br>'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <input type="text" /><br> <input type="text" /><br> <input type="text" /><br> </div> <button>Create one more</button> 

您不需要复杂的生成ID,也不一定需要一个类(除非您有不想与之冲突的其他input[type=text] )。 而且您无需复制代码并编写相同功能的20倍。 曾经 如果要复制代码,则说明您做错了。

提供一个代码段,可能会给您一些提示:

$(".add_field_button").click(function () 
{
    if (counter > 10) 
    {
        alert("Only 10 textboxes allow");
        return false;
    }
    var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");

     //creating the risk weight
     var txtBox1 = $('<input />', 
                           {
                            'id'     : 'fst_textbox_' + counter,
                            'name'   : 'textbox'+counter,
                            'type'   : 'text',
                            'class'  : 'input_field',
                            'onClick' : 'txtBoxFun(this,'+counter+')'
                          });
     var txtBox2 = $('<input />', 
                           {
                            'id'     : 'sec_textbox_' + counter,
                            'name'   : 'textbox'+counter,
                            'type'   : 'text',
                            'class'  : 'input_field',
                            'onClick' : 'txtBoxFun(this,'+counter+')'
                          });

    var txtBox3 = $('<input />', 
                           {
                            'id'     : 'sum_textbox_' + counter,
                            'name'   : 'textbox'+counter,
                            'type'   : 'text',
                            'class'  : 'input_field',
                          });

 $(txtBoxDiv).append(txtBox1).append(txtBox2);
 $(txtBoxDiv).append(txtBox3);
});

function txtBoxFun(obj, count)
{
   var idGet = $(obj).attr('id');
   var idArr = new Array();
   idArr = idGet.split("_");
   if(idArr[0] == "fst")
   {
      var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
   }
   else if(idArr[0] == "sec")
   {
      var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
   }
   $("#sum_textbox_"+count).val(sumTxt);

}

您可以为要在其上执行keyup事件的所有文本框分配一个class ,然后使用class将事件附加到具有class元素上。 这是一个例子

var html="";
for (var i = 0; i < 20; i++)
 {
   html += "<input type='text' id='txt" + i + "' class='someClass' />";
 }
 $("#testDiv").html(html);

keyup事件附加到具有someClass类的someClass

 $(".someClass").keyup(function () {
  alert($(this).attr("id"));
 });

可以与您最喜欢的答案结合的小帮手:

var uid = function () {
    var id = 0;
    return function () {
        return ++id;
    };
}();

用法:

uid(); // 1
uid(); // 2
uid(); // 3

将类“ a”和“ b”添加到文本框,将“ box”添加到框中。 然后添加带有索引的data-idx属性(未使用!?)。 最后注册事件处理程序:

 $('.a').on('keyup', function(e){
    e.preventDefault();
    var $this = $(this)
    var $p = $this.parent()
    var a= this.value; 
    var b= $p.find('.b').val()
    var number =$this.data('idx') //unused!?
    var result = check(a,b)
    $p.find('.box').val(result)
 })
 $('.b').on('keyup', function(e){
    e.preventDefault();
    var $this = $(this)
    var $p = $this.parent()
    var a= $p.find('.a').val()  
    var b= this.value
    var result = check(a,b)
    $p.find('.box').val(result)
 })

还是一般的:

 $('.a,.b').on('keyup', function(e){
    e.preventDefault();
    var $p = $(this).parent()
    var a= $p.find('.a').val()  
    var b= $p.find('.b').val()
    var result = check(a,b)
    $p.find('.box').val(result)
 })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM