HTML code inside JQuery html method not working (it shows the content but the javascript call is not working)

Viewed 47

To start I'm still learning javascript and AJAX so feel free to say everything that you want :)

I really don't get why this is happening: I have an Ajax function working very well, but if I post html content to call it again the AJAX function won't work in the content that it previously posted.

So here's the html code:

<div id="left-content">
<a class="clickme" value="1"> Option 1</a>
</div>

And this is my function

(function($) {
$('.clickme').click(function() {
    $.ajax({
        url: options.ajaxurl,
        method: "POST",
        data: {
            "action": "filter",
            "selection": $(this).attr('value')
        },
        beforeSend: function() {
            $('#left-content').html("Loading...");

        },
        success: function(data) {
                let html=``;
                html+=`<a class="clickme" value="1">
                Option 1 again
                </a>`:
                $("#left-content").html(html);
        },
        error: function(error) {
            console.log(error)
        }
    })
})
})(jQuery);

So what I get after clicking Option 1 is

<div id="left-content">
<a class="clickme" value="1"> Option 1 again</a>
</div>

But if I click this it won't work now :( .

1 Answers

I think I see the problem: In the data property of your ajax object you set selection as

   selection": $(this).attr('value')

the anchor tag does not have a value attribute, it has val. Rename val to value and it should work

    <a class="clickme" value="1"> Option 1 again</a>
Related