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...
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With