The goal is, when I focus on the last text line, another one appears below it. Then disable this at a certain number of lines. I can't seem to figure out what is wrong here:
$(document).ready(function() {
lineCount = 0;
$("form#qc").delegate("input:text:last-child", "focus", newTextLine);
});
function newTextLine() {
newLine = ("<div id='ansInput{0}'>Answer {0}: <input type='text' name='ans1' /></div><!--ans1-->").format(lineCount);
currentDiv = ("#ansInput{0}").format(lineCount);
$(currentDiv).after(newLine);
lineCount = lineCount++;
}
this is the HTML page:
<form id="qc" name="qc">
<h2>Create New Question!</h2>
<div id="ansInput0">Question: <input type="text" name="Question" /></div><!--question-->
<input type="submit" value="Submit" />
</form>
I get a very very weired result: each time two lines appear and all have index of 0
and all respond the event handler that is suppose to work only for the last one...
Any ideas what's wrong with the code?
Also any advice on how to make the code smarter is welcome!
As said, there are some problems in your code. I'd try it like this: Cloning the last div, changing the id and clearing the value of the input:
$(function() {
$("#qc>div:last-of-type>input").live('focus', function() {
$(this).parent().after($(this).parent().clone().attr('id', 'ansInput' + $('#qc>div').length).find('input').val('').end());
});
});
i hope this wasn't too confusing! :)