Search code examples
jquerydynamiccontrolsauto-generate

Jquery get dynamically generated Id of control


I have a page where Ids are changed to ctl00_MainContent_txt_insurance. In this case I cannot use the actual Id as $("#txt_insurance"). so what I did was to use $("#<%= txt_insurance.ClientID %>"), which works fine now.

But now if I want to replace the above ID and show it I did this:

divToChangeVisible = $("#<%= txt_insurance.ClientID %>");
divToChangeVisible.replace("txt_", "val_").show();

This will get me an object and throws an error saying cannot be replaced. Is there a way to get txt_insurance as Id without having to replace ctl00_MainContent_?

Edit :: If I do $("#<%= txt_insurance.ClientID %>").attr('id') this will again return the dynamic id...


Solution

  • you can use Jquery selector like "ID ends with":-

    $("[id$='txt_insurance']")
    

    above statement fetch the element whose ID ends with "txt_insurance".

    for an example :-

    var eleid=$("[id$='txt_insurance']").attr('id');
    var rep=eleid.replace("txt_", "val_");
    alert(rep);
    $("[id$='txt_insurance']").attr('id',rep);
    //this will replace old ID with new which is 'ctl00_MainContent_val_insurance'
    

    UPDATE:-

        var ele=eleid.split("_");
    alert(ele[ele.length-2]+'_'+ele[ele.length-1]);
        var originalid=ele[ele.length-2]+'_'+ele[ele.length-1];
        // originalid will give you original id of element :-
    

    so you can proceed like :-

    $('.myform :input').each(function () 
    {
        var id = this.id; 
        var orgid=id.split("_");
        var orgid1=orgid[orgid.length-2]+'_'+orgid[orgid.length-1];
        var id2 = $("[id$=" + orgid1 + "]");
     });