I've got a new product form with dynamically created textbox for "Available Color". What I want to do is assign focus on the new textbox. Here's my code.
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function () {
colorCounter = 2;
sizeCounter = 2;
$("#addColorButton").click(function () {
if (colorCounter > 10) {
alert("Only 10 colors allowed");
return false;
}
//This has been edited to show the solution
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'ColorTextBoxDiv' + colorCounter);
newTextBoxDiv.after().html('<label>Color #' + colorCounter + ' : </label>' +
'<input type="text" name="AvailableColor' + colorCounter +
'" id="colorTextbox' + colorCounter + '" value="" >');
newTextBoxDiv.appendTo("#ColorTextBoxesGroup");
$('#colorTextbox' + colorCounter).focus();
colorCounter++;
});
});
});
</script>
<form name="newProductForm" id="newProductForm" action="index.cfm" method="post">
<div id='ColorTextBoxesGroup'>
<div id="ColorTextBoxDiv1">
<label>Color #1 :</label>
<input type='text' id='colorTextbox1' name="AvailableColor1" />
</div>
</div>
<input type='button' value='Add More Colors' id='addColorButton'>
</form>
var myTextbox seems to evaluate to "colorTextbox2" after the first click but the focus does not move to the newly created textbox.
If I change the line $('#myTextbox').focus(); to $('#colorTextbox2').focus(); then the focus is moved to the new textbox. Of course another button click and the focus stays in textbox2.
I would sure appreciate some help on this. Thanks!