简体   繁体   中英

How to get attribute of dynamically generated element ASP.NET

I know there are tons of questions on this topic and I've tried many of them to no avail. If anyone has any suggestions, it would be greatly appreciated. I'm trying to get the inputs' id attribute. I've stripped the code to just focus on the issue.

The cshtml:

@for (var i = 0; i < Model.DieRouteChecks.Count; i++) 
{
    <div class="col-9">
       <div class="form-group newThresholdInput">
          <input asp-for="@Model.DieRouteChecks[i].NewDieThresh" class="form-control" id="@Model.DieRouteChecks[i].Description">
       </div>
    </div>
}

My javascript:

$(".newThresholdInput input").click(() => {

        console.log($(this).attr("id")); //To see what's being returned

        switch ($(this).attr('id')) {
            case "Order Value":
                  //Do stuff
                  break;
            case "Order Quantity":
                  //Do stuff
                  break;
            }
        })

I keep getting undefined logged when clicking the input. I've tried

$(".newThresholdInput").click(() => {
    console.log($(this).find("input").attr("id"));
}

And it printed out only the first input element's id. I've also tried using onclick="function(this)" and creating an event-handler that's called in the script tags but still nothing.

What's funny is console.log($(".newThresholdInput input").attr("id")) logs Order Value as it should so I'm guessing it has something to do with how I'm using $(this) .

I'm sure I'm just missing something small but I don't know what it might be.

In your click event, this represents the whole Window so that it cannot find your clicked element.

Change your js to:

@for (var i = 0; i < Model.DieRouteChecks.Count; i++) 
{
    <div class="col-9">
       <div class="form-group newThresholdInput">
          <input asp-for="@Model.DieRouteChecks[i].NewDieThresh" class="form-control" id="@Model.DieRouteChecks[i].Description">
       </div>
    </div>
}
@section Scripts {
    <script>    
        $(document).on('click', '.newThresholdInput input', function () {
              var index = $(this).attr("id");
              console.log(index);
        });
    </script>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM