0

I need help with some Javascript.

Inside my html I have a form that repeated twice.

<form method='post' action='php page'>
   <input type=text id=something name=something value='' />
   <input type="submit" id="final_submit" value="yes">
</form>

This exact form is repeated twice. In javascript when someone clicks on the submit button I need to be able to determine which button was clicked to get the value of something in that form. Right now its automatically just getting the value for the first form even though I click the button on the second form.

Any ideas please.

4

2 回答 2

0

Is that what you need?

function determineForm(e)
{

 // This prevents the form from actually being submitted.
 // Just remove it when you are done debugging.
 e.preventDefault();

 if (document.querySelectorAll("form")[0] === e.target)
 {
  alert("Form1");
 }
 else
 {
  alert("Form2");
 }
}
document.addEventListener("submit", determineForm, false);
于 2012-09-05T18:01:22.407 回答
0

As mention in the comments, using duplicate id is wrong. Here is a way to get the value of the input that will work also in using older browsers document.forms and forms.element

var forms = document.forms;
for(var i=0, l= forms.length; i++){
  forms[i].addEventListener('submit', function(e){
   e.preventDefault();
   var form = e.target;
   var value = form.elements[0].value;
  })
}

This will add a submit event listener to every form in your side and that stops the event and get the value from the first input field in this form.

于 2012-09-05T18:27:03.437 回答