Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - jQuery not posting all inputs of a form after the .append()

I have a form generated dynamically with the method .append() of jQuery. I can add any number of new input, textbox, cmbbox, etc...

But the problem is that when I do the sumbit of the form, the PHP target does not receive the new input added, but just the vars connected to the input already in the form before the append().

Any ideas?


The javascript:

$("#button").live('click',function add(){
   $("#list").append(
       '<li style="height:20px;">'
    +'<input type="text" class="text" id="prova" name="prova[]" value="prova">'+ 
       '</li>'
   );
});


The Html:

<input type="submit" id="button" value="Add input">
<form name = "form" id="form" action="post.php" method="POST">
   <ul style="width:670px;padding:0px 0px 30px 0px" id="list">
   </ul>
   <input type="submit" id="submit" value="Submit">
</form>


The PHP:

<?php
  print_r($_POST);
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem 1:

Your #button should not be of type submit, since you just want to use it to add to the form and not submit the form. So you should have:

<input type="button" id="button" value="Add input">


Problem 2:

You are overwriting your variables. The name is the variable sent with the form, so each input addition must have a new name, or the variable must be an array.

Additionally, you can't have more than one element with the same id.

The simplest way to solve this is to make prova an array by using the form prova[]:

$("#button").live('click',function() {
   $("#list").append(
       '<li style="height:20px;">' +
         // Removed repetitive ID and made prova an array
       '<input type="text" class="text" name="prova[]" value="prova"></li>'
   ); 
});

jsFiddle example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...