SpoiledTechie.com
SpoiledTechie.com

Reputation: 10735

Setfocus to textbox from JavaScript after just creating the textbox with JavaScript?

So I just created a textbox with JavaScript like this:

EDIT: Added the len variable

var len = tbl.rows.length;
                     var rtb = tbl.insertRow(len);
                     var cName = rtb.insertCell(0);
                     var cDis = rtb.insertCell(1);
                     var cDur = rtb.insertCell(2);
                     cName.innerHTML = '<input type="text"  name="tbName1' + len + '" value="' + selected_text + '" >';
                     cDis.innerHTML = '<input type="text" name="tbDis1' + len + '" id="tbDis1' + len + '" >';
                     cDur.innerHTML = '<input type="text"  name="tbDur1' + len + '" >';
                     var txtBox = document.getElementById('tbDist1' + len);
                     txtBox.focus();

EDIT:Changed the second to last line. Still get this error: txtBox is null txtBox.focus();

The last line isn't working. After I create the textbox, I can't set focus to it. Is there any way of doing so?

Upvotes: 0

Views: 8793

Answers (6)

jjj
jjj

Reputation: 605

I can't call the textbox and idk. Why?!!

--> var txtBox = document.getElementById('tbDist1' + len);

Upvotes: 0

jjj
jjj

Reputation: 605

I have this simple code:

<html>
<body>
<form id="f1">

<asp:Label id="tt"  runat="server" Text="Label" onclick="lblClick()"></asp:Label>

</form>
<script type ="text/javascript">

          function lblClick() {
             document.forms[0].tt.Text ="java";// here is the problem .. and idk why?
          }
</script>
</body>
</html>

Upvotes: 0

olliej
olliej

Reputation: 36793

Err, it looks like a typo. You're asking for (afaict) tbDist1, but creating tbDis1.

[Edit: marius also spotted len vs len-1 which I missed.]

Upvotes: 0

Marius
Marius

Reputation: 59009

If you check the value of txtBox you will see it is undefined. You try to get the element with id tbDist1 + (len-1), but you create an element with id tbDis1 + len.

Upvotes: 1

Paolo Bergantino
Paolo Bergantino

Reputation: 488714

Hum... you're creating the textbox by saying id="tbDis1' + len + '" but you're accessing it by doing 'tbDist1' + (len - 1)... why? I am not sure about the context, but that would try to focus the previously added textbox, if any. Also, you're creating it with tbDis and trying to get to it by using tbDist. Missing a t in there. Setting the id as id="tbDist1' + len + '" and accessing it with 'tbDist1' + (len) should do the trick.

Upvotes: 1

Ilya Birman
Ilya Birman

Reputation: 10102

Not sure how it is supposed to work: you have tbDis and len before, then tbDist (notice: t) and len-1 after. Weird... :-)

Upvotes: 0

Related Questions