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 !
btn.on('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);
}
});
});
Try that, just use "on" ;)
If your alert works before that should be great
Why are you mixing jQuery and JS-plain so much? Use jQuery for the event binding ... and call you function some where:
function attachEventsFid2() {
var main= $('.main-wrapper');
var btn = $("#btn-iphone4");
btn.on('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);
}
});
});
};
//Call it...
attachEventsFid2();
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/