2

I have PHP that searches a database and then echoes an html form for each result found. These are loaded via AJAX into the main HTML page into a div on document load.

Now I want to have listeners for each of these forms submitting. They all have the same inputs. Each form has an incremental ID of processor (processor1, processor2, processor3, and so on).

So, depending on the results, it could be as little as one form or 50 forms. Is there a dynamic way of doing a form submit function rather than writing countless repetitive functions?

2
  • what do you mean by "doing form submit function"? Commented Nov 4, 2013 at 23:50
  • $("#processor1").on( "submit", function( event ) { Commented Nov 4, 2013 at 23:52

2 Answers 2

2

If you have

<form id="form1">
<form id="form2">

You can use a class selector

<form id="form1" class="forms">
<form id="form2" class="forms">

In jQuery:

$(function() {
 $('.forms').submit(function(e){
   e.preventDefault(); //Prevent submit
   console.log($(this)); //Current form submiting

   //Make ajax call for current form
 })
})

If u you need extra data for each form, you can use data atributte

<form id="form2" class="forms" data-myattr="myvalue">

And get it

...
$(this).data('myattr'); //myvalue
...
Sign up to request clarification or add additional context in comments.

3 Comments

If I wanted to use input values for only the submitted form, would I do this? $("this .inputclass").val(); instead of $("#form1 .inputclass").val();
$(this).find('.inputclass').val() will do.
$(this) is the current form object. You can use $(this).find("selector") to search elements in the form.
0

If using classes is (for some reason) not an option, you can also use 'starts with' selector:

$('#processor*').submit(function (e) { 
    e.preventDefault(); 
    ...
});

Note that the above function should be called as a callback to AJAX function that loads the forms.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.