简体   繁体   中英

Dynamic add divs to html using js

I am trying to add html divs( with textfields) using button click.My form look like this : 在此处输入图片说明 On add size button click it add one row ( Price and size ) and one add More item button click i want to add new area with name , price and size and so on. HTML Code is :

<div class="clearfix"></div>
                    <div class="moreitems form-group" style="border:1px solid #ccc;height:200px;display:none;">

                     </div>

My js code is :

jQuery("#addmoreitems").click(function () {
    var options = jQuery("#select1").html();

jQuery('.moreitems').css("display","block");
    var fld = '<div class="clearfix"></div><div class="form-group"><div class="col-sm-3"><label for="" class="text-left control-label">Product Name :</label></div><div class="col-sm-4"><input type="text" class="required-entry form-control" name="pname[]" id="pname"></div></div></div>';
   fld += '<div class="clearfix"></div><div class="form-group"><div class="col-sm-3"><label for="" class="text-left control-label">Price :</label></div><div class="col-sm-4"><input type="text" class="required-entry form-control" name="more_prices[]" id="prices"><select name="more_size[]" class="mysize">'+options+'</select></div></div>';
   fld += '<div class="col-sm-4"><div class="col-sm-3" style="margin-top:15px;"><button type="button" id="addsize" class="btn btn-info">Add Size</button></div></div>';
jQuery('.moreitems').html(fld);
jQuery('.mysize').html(options);


    });
});

But this code add first time.I want to add as many times the add more items button.Also on add more size button want to add price and size fields.

The problem is that you're using html() function which replaces the entire html contents, where in your situation you want to append() the HTML every time you click the button.

Change:

 jQuery('.moreitems').html(fld);

To:

 jQuery('.moreitems').append(fld);

Hi as i know the may the problem is in appending the using the .html() method.

here the difference between this two methods reference link given

http://www.slideshare.net/umarali1981/jqueryappend-vs-jqueryhtml

cause .html() overwrites the contents of the DIV. while .append() will add to the contents of the DIV. so use this and another thing to notify is that you should bind the 'click' event in-spite of using the only 'click' method like.

 $("#addmoreitems").unbind('click').bind('click',function () { // write your code here }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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