Paul Paul - 2 months ago 11
jQuery Question

JS - use preventDefault instead of return false

Not great with Js so looking for some help with some existing code.
I have the following anchor

<a href="#" class="addroom" onclick="return false;"><span>Add</span></a>


I am getting a warning regarding the 'onclick' event where its telling me that i dont have keyboard equivilant handler for the the onclick="return false; I have done some research and i can prevent this warning by using preventDefault. if i put this in a script tag in the page then it works the same and i think it will get rid of the issue.

$("a.addrom").click(function(e) {
e.preventDefault();


});

However, i would prefer to add it to the existing js but im having a hard time working out whats going on. I am trying to add it to the click event.

setupRooms: function (settings) {
//hide all age fields
$(settings.agesSelector, settings.hotelSearchDiv).hide();
//hide all except first
$(settings.roomsSelector + ":not(:first)", settings.hotelSearchDiv).hide();
$('select', settings.hotelSearchDiv).prop('selectedIndex', 0); //set all to 0
$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function () {
methods.addRoom(settings);
});
$(settings.removeRoomSelector, settings.hotelSearchDiv).on('click', function () {
var id = $(this).data('id');
methods.removeLastRoom(settings, id);
});

$(settings.childrenNumberSelector, settings.hotelSearchDiv).on('change', function () {
methods.handleChildrenChange(settings, $(this));
});
},


Edit* This code worked for me thanks to @patrick & @roberto

$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
e.preventDefault();
methods.addRoom(settings);
});

Answer

If i understood correctly you want to add that on your click handlers:

$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
     e.preventDefault();
     methods.addRoom(settings);
});
$(settings.removeRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
     e.preventDefault();
     var id = $(this).data('id');
     methods.removeLastRoom(settings, id);
});

Should be enough for having the prevent default in your click handlers.

Cheers