I’ve a table where I dynamically add textbox and button, also an ajax function that returns a value by sending the textbox string to the controller where it does all the processing.
The code works fine if it’s just a single textbox but adding N textbox doesn’t work, what should I modify to make the ajax function work with each desired textbox? That is to say
If I want to send the value that is in textbox #2 with its respective button and when clicking on it (btnSearch), what is in textbox #2 is sent and not in number #1
Table code
<a href="#" id="addNew" style="text-align:right;float:right"><input type="button" value="Add record" style="height: 30px;width: 110px;font-size: 0.75em" /></a>
<table id="dataTable">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
int i = 0;
//foreach (var p in Model.TBHDR)
for (i = 0; i < Model.TBHDR.Count && i < Model.TBDTL.Count; i++)
{
<tr>
<td>@Html.TextBoxFor(mod => mod.TBHDR[i].PR_REQ_OWNER, new { id = "hdr_req_owner", @class = "own" })<input type="button" value="Search" id="btnSearch" /></td>
<td><a href="#" id="remove" class="remove" name="pr_remove">Remove</a></td>
</tr>
}
</tbody>
</table>
Ajax function
$('#dataTable').on('click', '#btnSearch', function (e) {
$.ajax({
url: "@Url.Action("GetOwner", "PR_Creation")",
data: { ownerName: $('#hdr_req_owner').val() },
type: "GET",
dataType: "json",
success: function (data) {
$('#hdr_req_owner').val(data)
},
error: function () {
alert("Failed! Please try again.");
}
});
});
2
Answers
$(‘#hdr_req_owner’).val() this function always return only first element in DOM. so always you are getting first input value.
Don’t repeat same ID use classes etc..
try to catch the parent of button on click and than use jQuery find method to get the input field. hope it will work.
So as I mentioned in the comment, you need to find which element clicked, and use that element.