0

I researched how to submit a form via javascript but, in my case, I'm creating several forms based on a collection of data. I don't know the best way to reference the form ID.

<c:forEach 
    var="meeting" 
    items="${response.mMeetingList}"
    begin="0"
    end="5">

    <div class="row">

        <ul class="span4 unstyled">
            <li>
                <form name="mtgDetailsForm" action="/transporter/app/meeting/read" method="POST">
                <input type="hidden" name="meetingId" value="${meeting.meetingId} }">
                <a href="javascript: getMtgDetails()" class="row">
                    <div class="span1"><fmt:formatDate value="${meeting.startTime}" type="time" pattern="h:mm a"></fmt:formatDate></div>
                    <div class="span3">${meeting.meetingName}</div>
                </a>
                </form>
            </li>
        </ul>

    </div>

</c:forEach>

And here's the JS method for submitting the form:

function getMeetingDetails( data ){
        document.mtgDetailsForm.submit();
    }

Obviously, this will not work because the form ID will be duplicated. What's a better approach?

Thanks for any tips!

fumeng
  • 1,771
  • 5
  • 22
  • 61

2 Answers2

1

You can reference the form from a, example on jsFiddle

function sub(e)
{
    var f = e.parentNode;

    // if using jQuery prefer this method to access `form`
    // var f = $(e).closest("form");

    f.submit();
}

Then

<a href="#" onclick="sub(this)">Submit</a>
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • This is fragile (will break if the event origin is not an immediate child). I prefer [`.closest("form").submit()`](http://stackoverflow.com/a/419111/309483) – Janus Troelsen Jun 04 '13 at 17:45
  • @JanusTroelsen me too, but he is not using jQuery I guess, and it would overly complicate the answer to implement it with pure js – BrunoLM Jun 04 '13 at 17:47
1

I dont know the code you are using to generate the dynamic forms, but one approach would be to generate one id for each form, something like this:

 <form name="mtgDetailsForm${counter}">

Pass the form id by parameter to function

<a href="javascript: getMtgDetails('mtgDetailsForm${counter}')" class="row">

Get the form and submit it based in the parameter

function getMeetingDetails( formId ){
        document.getElementById(formId).submit();
    }

Also need to increment the counter inside the for loop ${counter++}

fmodos
  • 4,472
  • 1
  • 16
  • 17