1

I'm developing a Wordpress site that (of course) is composed of multiple PHP templates. The particular template fragment I'm having problems with is called with this line:

<script id="templatehidden">                                    
    <?php get_template_part( 'fragments/calculator', 'row-sa' ); ?>
</script>

And the contents of calculator-row-sa.php are:

<div class="form-row pricingrow select-multiple">
<div class="form-controls"> 
<img class="remove-field-sa" style="float: left; margin-right: 30px;" src="http://45.32.89.214/wp-content/uploads/2016/04/minus.png">
<i style="margin-left: 50px;" class="cardinal"></i>
    <select name="field-followers[]" class="select followerselect">
        <?php foreach ( $options as $option ) : ?>
            <option value="<?php echo $option[ 'value' ] ?>"><?php echo $option[ 'label' ] ?></option>
        <?php endforeach; ?>
    </select>
    <b class="fa fa-caret-down" aria-hidden="true" style="color: #747474";></b>     
    <span class="acctprice"></span>
</div><!-- /.form-controls -->

And the jQuery code behind it is

$('.remove-field-sa').click(function () {           
        $(this).closest('.form-row').remove();
    });

My problem is with the img element inside the php. When the page first loads, it does its job and removes the row it's on. However, after I add more rows, no javascript code seems to execute within .form-content anymore. Any ideas on what's wrong?

1 Answer 1

2

Assuming that you are adding the rows using javascript, you need event delegation: At the moment you bind your even handler, the elements don't exist and when you add them, the click event is not automatically binded to these new elements unless you use event delegation.

You can easily change that using for example:

$('.form-content').on('click', '.remove-field-sa', function () {           
    $(this).closest('.form-row').remove();
});

Note that here the .form-content element has to be present on page-load. If it is not, you could also use something like:

// Any parent element that is present at page-load and will contain the child elements will do.
$('body').on('click', '.remove-field-sa', function () {           
    $(this).closest('.form-row').remove();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Nice. isn't the delegate function also possible? maybe just in case the jquery gets updated later on.
@baboizk Yes, but note that on() is not deprecated. Are you perhaps thinking of live()?
Yes, that's it ! live() got replaced by on(). apologies
Thanks a lot! It worked! Looks like I've got a lot to learn about events, handlers and delegations, but at least, for now, it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.