Greg Gum Greg Gum - 24 days ago 6x
HTML Question

How to set focus to textbox without using an id to specify which textbox

I have this html

<input />
<span ondblclick="setFocusToInput()">42</span>

method, how do I set the focus to the input?

This sample is highly simplified. The actual html is a treeview. The treeview can have the above repeated many times. Thus I cannot use an id on the div, the input, or the span.

The only reference I actually have is the event which is generated by the ondblclick event. The only thing which is certain is that the textbox which comes directly before the span is the one associated with the span.

What is happening in the treeview is that the user doubleclicks the span (which is the treeview text) and the treeview then unhides the textbox so the user can edit the value.

I need to be able to set focus to this textbox.


You can modify your setFocusToInput function to take one parameter and call it by passing this as the parameter

  <input />
  <span ondblclick="setFocusToInput(this)">42</span>

Then in the function you get the parent node and find the first input field

function setFocusToInput(htmlNode)