Question

I need to open popup on click of anchor link with jquery.

here is HTML part

<a href="/waw/jvcc/customerSearch.htm" title="Clear Search" class="clearField" id="clearText">Clear Search</a>

here is Jquery

$("a.clearField").on("click", function(){loadclearSearchPopup()});

function loadclearSearchPopup(obj){
    var delay = '';

    $(obj).preventDefault;
    //popup open code goes here;
    return false;
} 

I know i can work around by replacing href with href="#" But i am curious why event.preventDefault and return false not working?

Any help

Was it helpful?

Solution

$(obj).preventDefault;

should be

e.preventDefault();

It's a method of the event, not a property of the jQuery object. Also, the reason that return false is not working is because you are not passing the return value back to the handler

$("a.clearField").on("click", function (e){
    var delay = '';
    // Prevents the link from being followed
    e.preventDefault();
    // Prevents following links and propagation (bubbling the event)
    // Note that this is a jQuery feature only. In standard DOM event handlers,
    // return false is the same as e.preventDefault()
    return false;
    // But you don't need both
});

OTHER TIPS

Because you have to attach it to event, not $(obj)

event.preventDefault()

@Juan's answer is correct (though I answered 15 sec earlier), but I'd like to show how to do it correctly with some changes to his code

$("a.clearField").click(loadclearSearchPopup);

function loadclearSearchPopup(e){
    e.preventDefault();
    // ... your code after preventing default action
}
  1. I didn't use anonymous function as far as you have all your code in loadclearSearchPopup()
  2. I used click instead of on('click', ...) assuming that you don't have a lot of links on your page with exactly the same functionality and you will unlikely change it's content
  3. I prevent action on 1st string because maybe later you will need to return some result or break it, and preventing on last string will not execute

Note, that you cannot pass arguments to your function, but you can handle them IN it

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top