Govind
Govind

Reputation: 979

Dynamic Button id and Handle button click in jquery

I have below view page in MVC 3

  for (int i = 0; i < Model.Count(); i++)
    {
    <li>Premium:@Html.Label(Model.ToList()[i].Premium, new Dictionary<string, object> { { "id", "TxtPremium" }, { "name", "[" + i + "].Premium" }, { "Class", "bold" } })

    @Html.ActionLink("Proceed", "Policy", "PolicyUC", new { policyNumber = Model.ToList()[i].ReferenceNumber }, 
    new { id = "BtnProceed"+i, name = "BtnProceed", @class = "gridButtons" })
    }

in browser the above view generated as below,

<label class="bold" id="TxtPremium" name="[0].Premium">
<a name="BtnProceed" class="gridButtons" id="BtnProceed0" href="somevalue">

<label class="bold" id="TxtPremium" name="[1].Premium">
<a name="BtnProceed" class="gridButtons" id="BtnProceed1" href="somevalue">

my jquery is as below,

jQuery().ready(function domReady($) {
    $('.topbar_menu a').removeClass("active");
    $('.topbar_menu #homeLi').addClass('active'); 


    $('#BtnProceed').click(function () {       
        var currDate = new Date();
        $('#TxtEffectiveDate').removeClass("outLineRed");
        $('#errorMsg').hide();
        $('#spMsgError').hide();
        $('#MsgSucc').attr("style", "background-color:#dfe5e6;");

        if (currDate < $("#TxtEffectiveDate").val()) {
            $('#TxtEffectiveDate').addClass('outLineRed');
            $('#spMsgError').show();
            $('#spMsgError').html(""Your effective date has already passed.");
            $('#MsgSucc').attr("style", "background-color:White;!important;");
            return false;
        }
        else {
            $('#TxtEffectiveDate').removeClass("outLineRed");
            $('#errorMsg').hide();
            $('#spMsgError').hide();
            $('#MsgSucc').attr("style", "background-color:#dfe5e6;");
        }
    });

});

The button id is generated dynamically, i need to pass the id to jquery, so that clicked button will execute the jquery.

So, how to pass the id in the below code,

$('#BtnProceed').click(function ()

the button ids would be BtnProceed0,BtnProceed1,BtnProceed2,BtnProceed3 etc.,

Upvotes: 0

Views: 1167

Answers (2)

Amin Jafari
Amin Jafari

Reputation: 7207

use this code:

$(document).on('click','#BtnProceed',function (){});

instead of:

$('#BtnProceed').click(function (){});

UPDATE:

if you need to get the label value use this code:

$(document).on('click','.gridButtons',function (){
    var labelVal=$(this).prev().text();
});

Upvotes: 2

Satpal
Satpal

Reputation: 133403

As you already added CSS class, You should use class selector.

$(document).on('click', '.gridButtons', function () {
    var id = this.id; //Get button ID
});

Note: IDs must be unique. You have use id="TxtPremium" multiple times, which makes your HTML invalid.

Upvotes: 2

Related Questions