Hi there,

I'm having a little trouble in 'Setting the cursor focus' on a text box, that I'm creating dynamically, when Clicked on a button (having the onccick attribute).

Detail:

I have this button

<INPUT TYPE="button" name="add_ans" STYLE="background-color:#CCFF00;width:50;height:30;" VALUE="Add Answer" onclick="generateRow()">

And this generateRow() javascript function.

var answer_count = 0;
function generateRow() {
  answer_count++;
  var order = 'order'+answer_count;
  var answer_text = 'answer_text'+answer_count;
  var score = 'score'+answer_count;
  var d=document.getElementById("answer_header");
  d.innerHTML+="<table border=0 cellspacing=1 cellpadding=1 width=630><tr><td><input type='text' name='"+order+"' size='6' onfocus='this.blur();' value='0'></td><td><input type='text' name='"+answer_text+"' size='70'></td><td><input type='text' name='"+score+"' size='6' onfocus='this.blur();' value='0'></td></tr></table>";
}

So everytime the button is clicked, I get 3 text boxes. First text box, and the last text box, I made them uneditable.

What I wanted to do was, setting the cursor focus in the second text box.

I tried putting,

var txtBox=document.getElementById('answer_text'+answer_count);
	if (txtBox!=null ) txtBox.focus();

inside the generateRow function, so as to grab the dynamic variable, and make that field to be focused (and therby setting the cursor there).

but this always comes up with the javascript error, saying its NULL.

Does anybody know a solution for this ? Please let me know if you have one.


Thanks
Kalpsen

Looks like, it's tougher than I thought ?.... I see, no replies yet !!...

No luck yet !!

Hi there,

All you need to do is give your second input an ID, and then set focus to that element, see line #9.

var answer_count = 0;
function generateRow() {
	answer_count++;
	var order = 'order'+answer_count;
	var answer_text = 'answer_text'+answer_count;
	var score = 'score'+answer_count;
	var d=document.getElementById("answer_header");
	d.innerHTML+="<table border=0 cellspacing=1 cellpadding=1 width=630><tr><td><input type='text' name='"+order+"' size='6' onfocus='this.blur();' value='0'></td><td><input type='text' name='"+answer_text+"' id='"+answer_text+"' size='70'></td><td><input type='text' name='"+score+"' size='6' onfocus='this.blur();' value='0'></td></tr></table>";
	document.getElementById(answer_text).focus();
}

Hope that helps!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.