user4815740
user4815740

Reputation: 311

Jquery post dynamic form

I have this piece of codes. It will generate multiple form dynamically. I would like to ask how to write to Jquery code to post only selected form. The $day actually come from database, to make it simple I just assigned it to 6 here.

php

<?php

$day = 6;

for($i=1; $i<= $day ;$i++){

    echo "<div class='item'>";
    echo "<form class='itineraryForm' id='itineraryForm$i'  method = 'post'>";
    echo "<table>";
    echo "<tr>";
    echo "<th>Time</th>";
    echo "<th>Activities</th>";
    echo "</tr>";
    echo "<tr>";
    echo "<td>";
    echo "<input type='text' class='i_field' name='time[]' value='' />";
    echo "</td>";
    echo "<td>";
    echo "<input type='text' class='i_field' name='activities[]' value='' />";
    echo "</td>";
    echo "</tr>";
    echo "</tbody>";
    echo "<input type='image' id='i_save_btn' src='img/save.png' value='SAVE' align='right'/>";
    echo "</table>";
    echo "</form>";
}
?>

js

$().ready(function () {
    $("#i_save_btn").click( function(e){
        $.post('inc/process.php', $(".itineraryForm").serialize(), function(data) {});
    });
});

Upvotes: 0

Views: 39

Answers (1)

Nishit Maheta
Nishit Maheta

Reputation: 6031

use below code .

it is call Event Delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

-> use i_save_btn as class. is always should be unique.

$(document).ready(function () {
  $(document).on('click',".i_save_btn",function(e){
    e.preventDefault();
    $.post('inc/process.php', $(this).parents('form').serialize(), function(data) {});
   });
});

Check DEMO

Upvotes: 1

Related Questions