0

The textbox should be filled up with values from the table when the dedicated button is pressed.

@Html.TextBoxFor(model => model.Users, new { @id = "Name" }) 

... there for I need a button in every line of the table.

@foreach (var user in Model.Users) { <tr> <td> <input type="button" value="get" id="btnTakeOver" class="btn btn-primary" /> </td> <td>@user.Id</td> <td>@user.Name</td> <td>@user.Email</td> </tr> } 

But I have the problem that the JavaScript doesn't know the variables @user.Name and @user.Email from the foreach block.

The JavaScript block.

@section Scripts { @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/jquery") <script> $(document).ready(function () { $("#btnTakeOver").click(function () { $("#Name").val(@user.Name); // val from inside the foreach loop $("#Email").val(@user.Email); }); }); </script> } 

Has anybody an idea how it works?

3
  • you could add the name and the email as data attributes on the button: <input type="button" [email protected][email protected] value="get" id="btnTakeOver" class="btn btn-primary" /> then in the click handler you can use eg: $(this).data("name") to get the name.CommentedJan 17, 2023 at 11:03
  • I also suggest to change the id of the button to be a class. since ID's need to be uniqueCommentedJan 17, 2023 at 11:04
  • Use jQuery .on and target your tr instead of the button itself. That way you'll get the entire row of values. Using an id attribute will be a pain.
    – GH DevOps
    CommentedJan 17, 2023 at 12:24

1 Answer 1

1

You can add the data into onclick event of the button:

<td> <input type="button" value="get" id="btnTakeOver" class="btn btn-primary" onclick="myFunction(@user.Name,@user.Email)" /> </td> 

js:

 <script> function myFunction(Name,Email){ $("#Name").val(Name); // val from inside the foreach loop $("#Email").val(Email); } </script> 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.