Asim Mahar
Asim Mahar

Reputation: 1410

Multiple JQuery different form selectors

I have two forms one and two, and based on which form is submitted I want to call a function based on that submitted value at the end of my logic.

I want to know if I can retrieve each selector as an array index, loop or a property or something to var = tagsOrAnswerers? And then maybe I can pass that argument onto my function which will be called.

<html>
     <form class="one">
         <input type="text" name="foo">
         <input type="submit" value="Submit">
     </form>
     <form class="two">
         <input type="text"name="boo">
         <input type="submit" value="Submit">
     </form>
</html>

<script>
       $('.one,.two').submit( function(){
       var fooOrBoo = $(this).find("input[name='foo'],[name='boo']").val();

       getBoo(ifBoo); //run this function if var fooOrBoo = 'boo';
       getFoo(ifFoo); //run this function if var fooOrBoo = 'foo';

});
</script>

Upvotes: 4

Views: 87

Answers (2)

madi
madi

Reputation: 5662

Give a common name for the answers for each form. I named it as "answer"

   <div class="forms">
             <form class="one">
                 <input type="text" name="answer">
                 <input type="submit" value="Submit">
             </form>
             <form class="two">
                 <input type="text"name="answer">
                 <input type="submit" value="Submit">
             </form>
</div>

Here is the script:

<script>
$('.forms > form').submit( function(){
   var data = $( this ).serializeArray();
   console.log(data); // gives the current data of the forms

  //using the data you can call whatever function you want using a switch statment
});
</script>

Upvotes: 1

Vanojx1
Vanojx1

Reputation: 5574

if you want a single event approach try this but it really depend on what your functions ve to do

 $('.forms > form').submit( function(e){
   e.preventDefault();
   var formN = $('form').index(this);
   switch(formN){
     case 0:
         alert("FUNCTION1");
       break;
     case 1:
         alert("FUNCTION2");
       break;
     //and so on.....
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="forms">
     <form class="one">
         <input type="text" name="foo">
         <input type="submit" value="Submit">
     </form>
     <form class="two">
         <input type="text"name="boo">
         <input type="submit" value="Submit">
     </form>
</div>

Upvotes: 1

Related Questions