Matt Knight Matt Knight - 3 months ago 7
Javascript Question

How to post the form selected when inside a foreach

I have some data that I need users to pick from. The values are wrapped up in a forEach with a form that posts the selected list item.

<ul id="results">
<% records.forEach(function(value) { %>
<li>
<form id="detailsForm" action="/search/detail" method="post">
<div>
Employee Id: <%= value.netId %>
Name: <%= value.FirstName%> <%= value.LastName %>
</div>
</form>
</li>
<% }); %>
</ul>


The javascript is simple:

<script type="text/javascript">
$("#results").on('click', 'li', function () {
document.getElementById("detailsForm").submit();

});
</script>


The problem is that no matter which record is chosen, the first result is always the one passed in the post. That makes sense since the form names are the same in the forEach.

document.getElementById("detailsForm").submit();


I need a better way to post only the list item that is clicked on. I thought about doing it differently and trying to get $(this).text(), but there is a ton of whitespace and carriage returns (not shown for clarity) and I really need to serialize the data.

Answer

I could imagine that your problem is using an id in a loop. Remember that id must be unique on the page! The generated HTML will probably include several forms with the same id, so with JavaScript getElementById you will always get the first one

EDIT: So remove the id of the form element. And change the JavaScript like that:

$("#results").on('click', 'form', function () {
        $(this).submit();
});