Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To really handle it correctly, you need something else, like this:</p> <pre><code>$(function() { $('#addImg').live('click', function(e) { for(var i=1; i&lt;5; i++) { if ($('#clone input[name="attachment_'+i+'"]').length == 0) break; if(i == 4) return false; } $('&lt;p&gt;&lt;label&gt;&lt;input type="file" name="attachment_'+ i +'" /&gt; &lt;a href="#" class="remImg"&gt;Remove&lt;/a&gt;&lt;/label&gt;&lt;/p&gt;').appendTo('#clone'); e.preventDefault(); }); $('#clone').delegate('.remImg', 'click', function(e) { if($('#clone input[name^="attachment_"]').length &gt; 1) { $(this).closest('p').remove(); } e.preventDefault(); }); }); </code></pre> <p><a href="http://www.jsfiddle.net/nick_craver/cMyXF/" rel="nofollow">You can test it out (seeing the generated HTML/nodes) here</a>.</p> <p>What this does it loop through and finds the first available <code>i</code> to use. Your original code <em>assumes</em> the last one is always the one removed, this may not be the case, and you'd still have a number repeated. Instead this loops though, gets the first available index and uses that...if we get to <code>4</code> and they were all in use, abort (you could add an <code>alert()</code> or something in that <code>if</code> as well, if you wanted).</p> <p>Also note the use of a class for <code>remImg</code> since it's repeated, and the use of <a href="http://api.jquery.com/delegate/" rel="nofollow"><code>.delegate()</code></a> to be a bit more efficient...you can also probably use just a normal <a href="http://api.jquery.com/click/" rel="nofollow"><code>.click()</code></a> handler on <code>#addImg</code>, but I'm not 100% sure of it's location here.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload