Jarla Jarla - 6 months ago 28
jQuery Question

How can I submit a sepecific form when I have multiple forms on my page?

I want to submit a form. Like this it is working very well:

<form>
<input name="name" value="somebody"><br>
<button type="submit" name="action" value="Submit" name="submit" >Submit</button>
</form>

<script>
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
submit($form);
});

function submit($form){
...do something....
}
</script>


But I have multiple forms on my page, so I am trying to do something like this:

<form name="myform">
<input name="name" value="somebody"><br>
<button type="submit" name="action" value="Submit" name="submit" >Submit</button>
</form>

<script>
$(document).on('submit','myform',function(e){
e.preventDefault();
$form = $(this);
submit($form);
});

function submit($form){
$.ajax('action.php', {
method: 'POST',
data: $form.serialize(),
success: function(result) {
$('#result').html(result);
}
});
}
</script>


But this is unfortunately not working. Do you know why?

Answer

This should get you started. You could also have different functions for each form submission.

function submit($form, action) {
  alert("Submitting form");

  $.ajax(action, {
    method: 'POST',
    data: $form.serialize(),
    success: function(result) {
      $('#result').html(result);
    }
  })
}

// Shorthand for $( document ).ready()
$(function() {

  $("#btn1").click(function() {
    alert("Submitting form 1");

    submit($("#frm1"), 'action1.php');
  });

  $("#btn2").click(function() {
    alert("Submitting form 2");

    submit($("#frm2"), 'action2.php');
    $("#frm1").submit();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm1" name="frm1">
  <input name="name" value="somebody">
  <br>
  <button type="submit" id="btn1" name="btn1" value="Submit">Submit Form 1</button>
</form>

<br>
<br>

<form id="frm2" name="frm2">
  <input name="name2" value="somebody else">
  <br>
  <button type="submit" id="btn2" name="btn2" value="Submit">Submit Form 2</button>
</form>