lovis91 lovis91 - 6 months ago 32
jQuery Question

jQuery addEventListener + ajax

I have a problem, my jQuery function doesn't work. It's initialize (alert before addEventListener works, but the click is not detected.
The tricks works with a

onclick="attachEventsFid2()"


But not with my code :

function attachEventsFid2() {
var main=$('.main-wrapper');
var btn = document.getElementById("btn-iphone4");

btn.addEventListener('click', function(event) {
event.preventDefault();
$.ajax({
type:"post",
url:BASE_URL+'index/formfid2/',
data:{'iphone':iphone},
cache:false,
success:function(data){
main.parent().html(data);
}
});
});
};


Html part :

<div class="row row3">
<a id="btn-iphone5" class="ico-reserver choix-iphone" type="button" value="iphone5" ></a>
</div>


Logs :

Uncaught TypeError: Cannot read property 'addEventListener' of null


With getElementsByClassName i have an other log :

Uncaught TypeError: undefined is not a function (=>
btn.addEventListener('click', function(event) { ... )


Thanks !

Answer

I found it working.

function attachEventsFid2() {
    var main=$('.main-wrapper');
    var btn = document.getElementById("btn-iphone4");

    btn.addEventListener('click', function(event) {
        event.preventDefault();
        alert('clicked');
    });
};

$(document).ready(function(){
    attachEventsFid2();
});

<input type="button" id="btn-iphone4" value="click"/>

Fiddle: http://jsfiddle.net/Wwb57/2/

FYI: your provided code is also working. Check this fiddle: http://jsfiddle.net/Wwb57/6/