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

问题描述:

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

i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks

这是我要解决的问题:

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

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

See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.

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

It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!

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

I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.

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

But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!

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

You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.

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" />