user2444474
user2444474

Reputation: 573

Anchor link function - onclick and href

I have anchor link with onclick and href functions. like below code

$("div.actions").append('<a id="excelExport" onClick="callajax();" class="actionButton" alt="Export to Excel" title="Export to Excel" href="partexport" ></a>')

function callajax() {
     jQuery.ajax({
     url : '<s:url action="partexport"/>',
     data : "fters.productNbr" : $("#productsTextArea1").val()} });

     }

Callajax is not at all calling when click the anchor link.

Upvotes: 1

Views: 586

Answers (3)

George
George

Reputation: 4413

There are a coulple things at play here.

  1. if you are using jquery already it is best to use jquery to attach the handler. Given this is an injected link it is tricky but my example covers how to do that.
  2. Your semi-colon is outside of the quotation marks for the onClick handler
  3. To avoid the default behavior of an anchor tag, all e.preventDefault(). This one isn't as big of a deal in your case as you dont redirect to an actual location but you might see odd behavior if you dont explicitly say 'dont do the default behavior'

http://jsfiddle.net/g30rg3/u5k95/3/

$(document).ready(function(){
    $("div.actions").append('<a id="excelExport" class="actionButton" alt="Export to Excel" title="Export to Excel" href="http://www.stackoverflow.com">click me</a>');
    $('div.actions').on('click.mylink', '#excelExport',function(e){
        e.preventDefault();
        callajax();
    });

});

function callajax() {
    alert('clicked');

}

Upvotes: 1

MrCode
MrCode

Reputation: 64526

The click event will be executed first and then depending on the result, the href will be executed. For example returning false from the click event will prevent the href from being executed.

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

The click handler will fire first. Depending on how to process your click, you can control whether the href link action goes through or not.

You can do both - i.e. have your click handler as well as the link action to go through. All you need to do is not return false or call event.preventDefault() from your click handler.

Upvotes: 2

Related Questions