Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  70] [ 5]  / answers: 1 / hits: 16659  / 15 Years ago, thu, december 10, 2009, 12:00:00

What I have is a single textbox. If the user hits the maxlength of it, I want to create a new textbox and then change focus to it so they can continue typing.


To accomplish this, I am trying to dynamically create textboxes that have an onkeyup event tied to them. To do this I am using document.createElement and the creation of the element works. The problem is that I can't get the parameters (the id of the current textbox and the id of the one to be created) to pass correctly and they are simply variables. Before I pass them I can test them and they are fine, but in the method they are null.


Here is my code:


 <script type="text/javascript">
var i = 2;
function CreateTextbox() {
var box = document.getElementById(divCreateTextbox);
var curr = 'txt' + i;
var next = 'txt' + (i + 1);

var inp = document.createElement('input')
inp.type = 'text';
inp.name = 'textfield';
inp.maxlength = '10';
inp.id = curr;
inp.setAttribute('onkeyup', 'moveOnMax(inp.id, next)');
inp.onkeyup = function() { moveOnMax(inp.id, next); };

box.appendChild(inp);
box.innerHTML += "<br />";

i++;

return next;
}

function moveOnMax(field, nextFieldID) {
if (field.value.length >= field.maxLength) {
if (document.getElementById(nextFieldID) == null) {
var id = CreateTextbox();

if (document.getElementById(id) != null) {
document.getElementById(id).focus();
}
else
alert("problem...");
}
}
}
</script>

<div id="divCreateTextbox">




I am pretty new to Javascript, so if this is completely fubar'd, I apologize.

Any help is appreciated.


More From » dom-events

 Answers
22
 <script type=text/javascript>
getId = function(){
var id = 1;
return function(){
id++;
}
}();

function CreateTextbox() {
var box = document.getElementById(divCreateTextbox);
var curr = 'txt' + getId();
var inp = document.createElement('input');

inp.type = 'text';
inp.name = 'textfield';
inp.setAttribute(maxlength,'10');
inp.setAttribute(id,curr);

box.appendChild(inp);

inp.setAttribute('onkeyup','moveOnMax(this)');
box.appendChild(document.createElement(br));
inp.focus();
}

function moveOnMax(s){
if(s.value.length >= parseInt(s.getAttribute(maxlength))-1){
s.blur();
CreateTextbox();
}
}

</script>


<div id=divCreateTextbox></div>

<script>
window.onload = function(){
CreateTextbox()
}
</script>
</html>

[#98097] Monday, December 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
piper

Total Points: 734
Total Questions: 93
Total Answers: 112

Location: Burundi
Member since Wed, Apr 6, 2022
2 Years ago
;