djs1 Posted June 3, 2011 Share Posted June 3, 2011 Hello, The code below allows a user to add new rows to a table, however I'm struggling with how to set a maximum limit on how many rows the user can add. I've tried to create a "while" loop, but haven't had any success. The ultimate goal is not only to limit the number of rows, but also to gray out, or change the class of the "add a row" link, so that the user is aware that they've reached the maximum limit. Can anyone show me what needs to be added to accomplish this? Thanks in advance! JavaScript Code of the Function: var next_row_index=2; function products_add_row() { var next_row_index,clone_row,clone,children,i,element,id,element_tbody;next_row_index=next_row_index;clone_row=document.getElementById('clone_row'); clone=clone_row.cloneNode(true); clone.id='products_row_'+next_row_index; clone.style.display=''; children=clone.getElementsByTagName('*'); for(i=0;i<children.length;i++) { element=children[i]; id=element.getAttribute("id"); if(id=='product_field') { element.id='product_field_'+next_row_index; element.setAttribute("name",'product_field_'+next_row_index); element.value='Add Product'; element.style.display='inline'; } } element_tbody=document.getElementById('products_tbody'); element_tbody.appendChild(clone); next_row_index++; } Code for the link that Creates the New Row: <a href="#" id="add_product" title="Add a New Product" class="add-product" onclick="products_add_row();return false;">Add a New Product</a> Quote Link to comment Share on other sites More sharing options...
arbitter Posted June 4, 2011 Share Posted June 4, 2011 What I do when I want to set a maximum is: var i = 1; while(i < 11){ //code to be executed with our var 'i' i++; } [/code] I'm not so into those for loops your using so I don't quite know if it does the same Hope it helps! Quote Link to comment Share on other sites More sharing options...
Adam Posted June 5, 2011 Share Posted June 5, 2011 Since all variables used within a arbitrary function are destroyed after execution, you need to store the number of added rows within a separate global variable. It's easy to do, just declare it outside of the function. Then when the function is called to add a new row, you can check this global variable isn't above a certain number. If it is, grey out the link and notify the user. If it isn't, then add the new row and increment the global variable. Edit Actually looking at your code, you're not far off that anyway. Just add a condition at the start of the function: if (next_row_index > 10) { // notify user return false; } // .... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.