Home > database >  How to get attribute of dynamically generated element ASP.NET
How to get attribute of dynamically generated element ASP.NET

Time:05-17

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 >
       <div >
          <input asp-for="@Model.DieRouteChecks[i].NewDieThresh"  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.

CodePudding user response:

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 >
       <div >
          <input asp-for="@Model.DieRouteChecks[i].NewDieThresh"  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>
}
  • Related