1

So for some reason I can't make jquery react on anchor click with class remove. The other function works just fine. I've tried changing it from class to id and it didn't work I've also tried changing id to the id of working function but it still didn't do anything.

<?php
    if(isset($_POST['submit'])){
        foreach($_POST['champion'] as $champion){
            echo $champion.'<br>';
        }
    }else{
?>
<a href="#" id="AddChampion">Add Champion</a>
<form name="second_form" id="second_form" method="POST">
    <div id="ChampionInput">
    </div>
    <input type="submit" name="submit">
</form>
<?php 
    }
?>
$(document).ready(function(){
    championNumber = 1;
    $('a#AddChampion').on('click',function(){
        $('#ChampionInput').append(
        '<a href="#" class="remove">Remove</a>\
         <br>\
         <input type="text" name="champion[]" placeholder="Champion '+championNumber+'">\
         <br>');
        championNumber++;
    });
    $('a.remove').on('click',function(){
        alert('test');

    });
});
1
  • just do $('#AddChampion').on('click', function(){}) Commented Jul 15, 2015 at 19:20

1 Answer 1

3

You have a href associated with your anchor. You need to update your code to

$('a#AddChampion').on('click',function(event){
    event.preventDefault(); // prevent the default handling
    .....
});

$("#ChampionInput").on('click', 'a.remove', function(event){
    event.preventDefault();
    alert('test');

});

For reference - http://plnkr.co/edit/Y2tiJf9u6kLR7lkiUuFT?p=preview

Sign up to request clarification or add additional context in comments.

2 Comments

Well now it works even without preventDefault and I don't fully understand why do we need a selector and child-selector
In your case you can skip preventDefault(), however, let us say if href is stackoverflow.com, then, in that case you will need preventDefault(). Additionally, for selectors, one word is event-delegation. For details can refer to another answer on stackoverflow - stackoverflow.com/a/22038965/1132354

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.