简体   繁体   中英

Trying to add a row dynamcially to a table and limit to 4 row using jQuery

I have a table which has no rows. And I am trying to add rows to by click of anchor tag and limit to 4. Once 4 rows are reached I want to show a alert box saying only 4 rows allowed. Right now it just keeps adding row even after limit 4 is reached. What am I missing

HTML CODE:

<table id="tbaddmore"></table>
    <div id="add-location"><a href="javascript:void(0);" class="addmore">Add one more location</a></div>

jQuery CODE:

 var i = 1;
 if (i == 4) {
     alert("only 4 allowed");
 } else {
     i++;
     $(".addmore").click(function() {
         $("#tbaddmore").append(
             '<tr><td><div class="pc-row"><div class="locations-colors pc-col"><label for="location_[' + i + ']"><span>Location</span><select name="location_[' + i + ']" id="location_[' + i + ']"><option value="">choose location</option><option value="front">Front Side</option><option value="back">Back Side</option><option value="left">Left Side</option><option value="right">Right Side</option></select></label></div></div></td></tr>');

     });
 }

I got it working my modifying the code to below

var i = 1;
 if (i > 4) {
     alert("only 4 allowed");
 } else {
      $(".addmore").click(function() {
         $("#tbaddmore").append(
             '<tr><td><div class="pc-row"><div class="locations-colors pc-col"><label for="location_[' + i + ']"><span>Location</span><select name="location_[' + i + ']" id="location_[' + i + ']"><option value="">choose location</option><option value="front">Front Side</option><option value="back">Back Side</option><option value="left">Left Side</option><option value="right">Right Side</option></select></label></div></div></td></tr>');
     i++;
     });
 }

Thanks again

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