I have a form in which I should be able to define multiple random amounts of people.
Instead I prepare the form rows in advance :
<div>Person 1: <label>Name:<input type="text"></label> <!-- rest of form elements --></div>
<div>Person 1: <label>Name:<input type="text"></label> <!-- rest of form elements --></div>
<div>Person 1: <label>Name:<input type="text"></label> <!-- rest of form elements --></div>
<div>Person 1: <label>Name:<input type="text"></label> <!-- rest of form elements --></div>
....
I would like to add some interaction:
The most desired way is to place an additional form whereby user can add person (html markup for presentation and hidden inputs for further $_POST handling) into existing part of form, without page reloading.
How should I go about it ?
I have three ideas:
click function
$('#addperson').click(function() {
//take values from form elements
var $form = $(this).parents('.passengersform')
var $name = $form.children('input.name').val();
var $phone ...
var $type ...
var $info ...
// append it
$('.passengers').append('<div> Here goes visible part of html</div>');
$form.append('<div>Here goes inputs type hidden for main form submit </div>');
// clear the form
});
Send / recieve data using AJAX :
echo resultappendd() / html() recived data when successClick button to append new row of form elements to fill them <- a bit differently than the picture above but still its better than empty slots
Perhaps you know of a plugin designed for this purpose?
In your form, add the attribute onsubmit to return a JavaScript function. Make sure that in the function, you do return false so the page does not refresh after the form submit.
<form onsubmit="return validate();">
And in your JavaScript, you can make a function that will do the validation with Ajax or not, and then append it to your list.
I made a quick example available here: JSFiddle
I used pure javascript to create the magic, trick is you need to get the control of form, which you can do using this button:
<button class="submit" onclick="return submtBtn()"type="submit">
javascript code is also quite catchy
function submtBtn(){
var tr="<tr>";
tr+="<td>"+document.getElementsByName('name')[0].value+"</td>";
tr+="<td>"+document.getElementsByName('Telephone')[0].value+"</td>";
tr+="<td>"+document.getElementsByName('Type')[0].value+"</td></tr>";
var table=document.getElementsByTagName('table')[0];
table.innerHTML=table.innerHTML+tr;
console.log(tr);
return false;
}
you are not letting submit the form because there is not need, and you are getting the work done. here is a working fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With