I have a following issue - I'm using jQuery to add additional input forms to the page. But added rows are not passed to the server with form submission.
Here is HTML of one row:
<form name="form1" method="post" action="">
<div id="input1" class="clonedInput">
<label for="answer1" class="answer_label"> Answer: </label>
<input type="text" name="answer1" id="answer1" value="Answ1"/>
<label for="answer1pt"> Points: </label>
<input type="text" name="answer1pt" id="answer1pt" size="2" value="1"/>
for cloning I use following JavaScript:
$('#btnAddAnswer').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.find(":nth-child(1)").attr('for', 'answer' + newNum);
newElem.find(":nth-child(2)").attr('id', 'answer' + newNum).attr('name', 'answer' + newNum).attr('value', '');
newElem.find(":nth-child(3)").attr('for', 'answer' + newNum + 'pt');
newElem.find(":nth-child(4)").attr('id', 'answer' + newNum + 'pt').attr('name', 'answer' + newNum + 'pt').attr('value', '');
$('#input' + num).after(newElem);
$('#btnDelAnswer').attr('disabled','');
if (newNum == 5)
$('#btnAddAnswer').attr('disabled','disabled');
});
So basically I first clone div with all content and then just adjust id's and other attributes.
The problem is that when running this code, everything displa开发者_如何学JAVAys on the page and seems ok, but when I submit the form, it appears that only first element is sent to the server.
This code perfectly works in Chrome and even IE, but not in Firefox. Any suggestions on what I'm doing wrong or what might cause this problem?
Thanks in advance!
Problem solved. Thanks Gazler, although there was no problem with actual HTML and Firefox error console didn't show any messages, I checked Developers Tools in Chrome and it said that div tag was inside table body, which, apparently, caused all the troubles.
Can I strongly recommend that you try to clean up your selectors by using classes instead of nth-child? It'll make all of your code a lot more readable. For example, if you had markup like:
<label class="answer-label" for="answer1">...</label>
<input type="text" class="answer-box" name="answer1" class="answer1" />
Then you could use this prettier Javascript:
newElem.find(".answer-label").attr('for', 'answer' + newNum);
Also, you might want to consider just storing one variable instead of num and newNum. That way, each time you can just do num++;
instead of doing var newNum = new Number(num+1);
. (I'm also not sure why you do new Number(num+1)
instead of just var newNum = num+1;
.
When in doubt, clean up your code and things might just fix themselves.
精彩评论