Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!