Search code examples
javascriptjqueryasp.netpostbacklinkbutton

How to obtain href attribute with jQuery


How would I be able to obtain the ID of a asp:LinkButton that has been modified by the master page so that I can simulate a click using javascript/jQuery ?

Normally, with this, I would obtain 'ctl05_butSaveAssociation' as the value for '_id':

function ClickSaveButton() {
        var _id = $('a[id$="butSaveAssociation"]').attr("ID");           
        __doPostBack(_id, '');
        return false;
    }

This doesn't work, because the ID changes again for some reason, as we can see using FireBug and hovering over the asp:LinkButton we have:

<a style="border-style: none; display: inline-block;" href="javascript:__doPostBack('ctl05$butSaveAssociation','')" class="CommandButton" id="ctl05_butSaveAssociation" onclick="SaveAssociation();" tabindex="0">Save</a>

So in fact, if I hardcode the right ID, it works with:

function ClickSaveButton() {
        var _id = "ctl05$butSaveAssociation";       // hardcoded
        __doPostBack(_id, '');
        return false;
    }

How could I implement this dynamically using jQuery?


Solution

  • While the HTML generated ids have _ (because are genereted based on the ClientID property), the ASP.NET helper methods expects $. I really don't know exactly why it can't use the underscore on all cases, but this is it...

    One easy thing is just using replace like _id.replace("_", "$"). Complete code:

    function ClickSaveButton() {
        var _id = $('a[id$="butSaveAssociation"]').attr("id");
        __doPostBack(_id.replace("_", "$"), '');
        return false;
    }
    

    But I'm here thinking... Why you just isn't calling the click event?

    function ClickSaveButton() {
        $('a[id$="butSaveAssociation"]').click();
        return false;
    }