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:
JavaScript
x
40
40
1
<script type="text/javascript">
2
var i = 2;
3
function CreateTextbox() {
4
var box = document.getElementById(divCreateTextbox);
5
var curr = 'txt' + i;
6
var next = 'txt' + (i + 1);
7
8
var inp = document.createElement('input')
9
inp.type = 'text';
10
inp.name = 'textfield';
11
inp.maxlength = '10';
12
inp.id = curr;
13
inp.setAttribute('onkeyup', 'moveOnMax(inp.id, next)');
14
inp.onkeyup = function() { moveOnMax(inp.id, next); };
15
16
box.appendChild(inp);
17
box.innerHTML += "<br />";
18
19
i++;
20
21
return next;
22
}
23
24
function moveOnMax(field, nextFieldID) {
25
if (field.value.length >= field.maxLength) {
26
if (document.getElementById(nextFieldID) == null) {
27
var id = CreateTextbox();
28
29
if (document.getElementById(id) != null) {
30
document.getElementById(id).focus();
31
}
32
else
33
alert("problem...");
34
}
35
}
36
}
37
</script>
38
39
<div id="divCreateTextbox">
40
I am pretty new to Javascript, so if this is completely fubar’d, I apologize.
Any help is appreciated.
Advertisement
Answer
JavaScript
1
44
44
1
<script type="text/javascript">
2
getId = function(){
3
var id = 1;
4
return function(){
5
id++;
6
}
7
}();
8
9
function CreateTextbox() {
10
var box = document.getElementById("divCreateTextbox");
11
var curr = 'txt' + getId();
12
var inp = document.createElement('input');
13
14
inp.type = 'text';
15
inp.name = 'textfield';
16
inp.setAttribute("maxlength",'10');
17
inp.setAttribute("id",curr);
18
19
box.appendChild(inp);
20
21
inp.setAttribute('onkeyup','moveOnMax(this)');
22
box.appendChild(document.createElement("br"));
23
inp.focus();
24
}
25
26
function moveOnMax(s){
27
if(s.value.length >= parseInt(s.getAttribute("maxlength"))-1){
28
s.blur();
29
CreateTextbox();
30
}
31
}
32
33
</script>
34
35
36
<div id="divCreateTextbox"></div>
37
38
<script>
39
window.onload = function(){
40
CreateTextbox()
41
}
42
</script>
43
</html>
44