Matt Knight Matt Knight - 1 year ago 46
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) { %>
<form id="detailsForm" action="/search/detail" method="post">
Employee Id: <%= value.netId %>
Name: <%= value.FirstName%> <%= value.LastName %>
<% }); %>

The javascript is simple:

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


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.


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 Source

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 () {