Jquery Append Input Field And Post
$('#submit').click(function(){ $.post( '/foo.php',{ name:myform.name.value, interest:myform.interest.value, interest2:myform.intere
Solution 1:
Are you setting form fields manually in your post request? Bad idea, you'd be better of using jQuery's serialize method:
$.post("/foo.php", $("#myForm" ).serialize() );
For your second question: use array naming on your form elements:
<inputtype="text" name="interest[]">
<inputtype="text" name="interest[]">
<inputtype="text" name="interest[]">
<inputtype="text" name="interest[]">
This way you get an array in your post array and can use it like so:
foreach ($_POST['interest'] as$interest) {
doStuff();
}
For your third question I'm assuming you wrote a JS method that adds an input field to the form? If so you could implement a limit this way:
window.formFieldCount = 1;
functionaddFormField() {
if (window.formFieldCount >= 3) {
alert('You can only add three interests!');
returnfalse;
}
// Do your form magic herewindow.formFieldCount++;
}
Solution 2:
HTML:
<form name="some_name">
<div id="interests">
<input type="text" name="interests[]" />
</div>
<input id="more-interests"type="button" value="Add more interest" />
<input id="submit"type="button" value="Submit" />
</form>
Javascript:
$(document).ready(function(){
var maximumNumberOfInterests = 3;
$('#more-interests').click(function(e){
if ($("input[name='interests[]']").size() < maximumNumberOfInterests) {
$('#interests').append('<input type="text" name="interests[]" />');
} else {
alert('The maximum number of interests has been reached!');
}
});
$('#submit').click(function(){
$.post('/foo.php', $('form').serialize());
});
});
PHP:
if (count($_POST['interests'])) {
foreach ($_POST['interests'] as$interest) {
echo$interest;
}
}
Here is a DEMO of the HTML/Javascript part
Solution 3:
q2. can you change form like this:
static inputs
<input name='static[something]'>
<input name='static[somebody]'>
<input name='static[etc]'>
and dynamically generated inputs
<input name='dynamic[]'>
<input name='dynamic[]'>
<input name='dynamic[]'>
php
if (isset($_POST['dynamic']))
{
foreach ($_POST['dynamic'] as$key => $value)
{
/* do some shit with dynamic inputs */
}
}
Solution 4:
Please use prepend function before form submit
Like
$("#myForm").prepend("<input type=\"text\" name=\"interest"+counter+"\"").submit(function(){
console.log($("#myForm" ).serializeArray())
$.post(Event.target.action, $(Event.target).serializeArray(), function(data){
// your code here
})
returnfalse;
})
Post a Comment for "Jquery Append Input Field And Post"