Greg Wiley
Greg Wiley

Reputation: 323

jQuery Add Item

So, what I'm trying to do here is onClick add another <li> that was exactly like the one above it. I have created a for loop in PHP to create the proper fields inside of this <li>.

The problem that I am running in to: When you click the .repatable-add button I get the "before replace" alert twice and the "after replace" alert does not fire at all. And ideas?

jQuery('.repeatable-add').click(function() { 
    field = jQuery(this).siblings('ul.image-details').find('li:last').clone(true);  
    fieldLocation = jQuery(this).siblings('ul.image-details').find('li:last');  
    jQuery('input', field).val('').attr('name', function(index, name) {
            alert(name +' before replace');
            return name.replace(/(\d+)/, function(fullMatch, n) {  
            return Number(n) + 1;  
            alert(name +' after replace');
        });  
    })  
    field.insertAfter(fieldLocation, jQuery(this).siblings('ul.image-details').find('li:last'))  
    return false;  
});  

Upvotes: 0

Views: 165

Answers (3)

Z2VvZ3Vp
Z2VvZ3Vp

Reputation: 7633

Not exactly sure what you're doing with that input part but I think it's because you're trying to do things after a return. Here's what I had:

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('.repeatable-add').click(function(){
            var copyThis = jQuery(".image-details").find("li:last").clone(true);
            jQuery(".image-details").append(copyThis);
            var name = jQuery("input").attr("name");
            var count = name.replace(/\d+/, '');
            var newCount = count++;
            jQuery("input").attr("name",name.replace(newCount.toString(),count.toString()));
        return false;  
    });  
});
</script>

<ul class="image-details">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<input name="ithas1" />
<button class='repeatable-add'>button</button>

Upvotes: 1

OnResolve
OnResolve

Reputation: 4032

Well, the alert for "after replace" is simply not firing since there is a return statement directly before it.

Upvotes: 1

Borgtex
Borgtex

Reputation: 3245

There's a return before the alert, so the alert will never be executed:

{  
            return Number(n) + 1;  
            alert(name +' after replace');
        });

Upvotes: 1

Related Questions