Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving values from for loop into jquery

How do I retrieve values from @for loop into jquery..Each value inside for loop should have different id, and jquery should get each separate id.... My for loop,

@for (int i = 0; i < searchList.Count;i++ )
{
    <label for="input@i"><input type="checkbox" id="input@i"/>@searchList[i]   </label>
}

My jquery which isn't helping,

  $("#input@i").on("click", function () {
    var currentChk = $(this);
    var propCheck = currentChk.prop("checked");
    if (propCheck) {
        debugger;
        var valChk = $("#input@i").val();
        alert(valChk);
    }
});

Thanks in advance...

like image 571
Michael Philips Avatar asked Oct 31 '22 04:10

Michael Philips


1 Answers

You can use Attribute Starts With Selector to bind the event.

$("[id^=input]").on("click", function () {
    var currentChk = $(this);
    var propCheck = currentChk.prop("checked");
    if (propCheck) {
        debugger;
        var valChk = $("#input@i").val();
        alert(valChk);
    }
});

As the id of both label and input-checkbox starts with 'input' the click event will bind to both of them. If you want to restrict you can add type to the selector, for instance you want only on checkbox you can change selector as under.

$("input[id^=input]").on("click", function () {...

or

$(":checkbox[id^=input]").on("click", function () {...

If you assign a class to the control you want to attach event then you can use class selector to bind the event.

@for (int i = 0; i < searchList.Count;i++ )
{
    <label for="input@i"><input type="checkbox" class="chk-class" id="input@i"/>@searchList[i]   </label>
}


$(".chk-class").on("click", function () {...

Edit As Mohamed-Yousef pointed you should use currentChk preferably or $(this) instead of $("#input@i") in statement $("#input@i").val(); as @i will not be the substituted value by C# loop but it will be added as string literal.

As a additional note you may use native javascript whenever possible and suitable e.g I would use this.checked instead of currentChk.prop("checked") to get the better performance, readability and simplicity.

$("[id^=input]").on("click", function () {   
    if (this.checked) 
    {
        //your code
    }
    else 
    {
        //your code
    }    
});
like image 107
Adil Avatar answered Nov 12 '22 16:11

Adil