How to dynamically add a div using JQuery?

前端 未结 3 1881
有刺的猬
有刺的猬 2020-12-28 11:02

I have the following html which displays 3 textboxes and an add button:



&l         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-28 11:27

    $(document).ready(function() {
        $('#imgBtnAddNewLineItem').click(function() {
            $('#container').append('
    '); }); });

    Update 2

    Create a normal button like so:

    
    

    Update ** This is also updated with comments etc.. **

    //Count the lineItems to make sure they are unique
    var lineItemCount = 0;
    
    //On document ready 
    $(document).ready(function() {
        //On button click
        $('#imgBtnAddNewLineItem').click(function(e) {
            /*
               ADD THE FOLLOWING LINE TO PREVENT THE POSTBACK
               P.S. - Make sure you pass -e- to this function... 
    
             */
             e.preventDefault();
    
    
    
             //Increase the lineitemcount
             lineItemCount++;
             //Add a new lineitem to the container, pass the lineItemCount to make sure getLineItem() can generate a unique lineItem with unique Textbox ids
             $(container).append(getLineItem(lineItemCount));
        });
    });
    
    //Create a new DIV with Textboxes
    function getLineItem(number) {
        var div = document.createElement('div');
        //Give the div a unique id
    
        div.setAttribute('id','lineitem_' + number);
    
        //pass unique values to the getTextbox() function
        var t1 = getTextbox('txt_' + number + '_1');
        var t2 = getTextbox('txt_' + number + '_2');
        var t3 = getTextbox('txt_' + number + '_3');
    
        div.appendChild(t1);
        div.appendChild(t2);
        div.appendChild(t3);
    
        return div;
    }
    
    //Create a textbox, make sure the id passed to this function is unique...
    function getTextbox(id) {
        var textbox = document.createElement('input');
        textbox.setAttribute('id',id);
        textbox.setAttribute('name',id);
        return textbox;
    }
    

提交回复
热议问题