Search code examples
javascriptinputonfocus

input type text onfocus function not calling


I have a table where each td element will contain a input type text.

<tr>
    <td id="a1"><input type="text" id="a1t"/></td>
    <td id="a2"><input type="text" id="a2t"/></td>
</tr>
<tr>
    <td id="b1"><input type="text" id="b1t"/></td>
    <td id="b2"><input type="text" id="b2t"/></td>
</tr>

I need to know the td id when text input is focused. I tried doing that by calling a js function with onfocus event attached to input type text, but the function is not getting called.

<input type="text" id="b2t" onfocus="cell_clicked('b2t')" />

Here is the function and a fiddle:

function cell_clicked(cell_no){
    alert(cell_no);
}

But the function is not getting called. Am i doing anything wrong?


Solution

  • Your code works fine, you have a setting wrong in jsfiddle.
    Under Framework and extensions change onLoad to no wrap to make your function cell_clicked globally available.

    See this http://jsfiddle.net/ywt8V/3/ (your fiddle http://jsfiddle.net/ywt8V/ with just this setting is changed).

    As a side-note, you could access the id of the parent table-cell like this:

    onfocus="cell_clicked(this.parentNode.id)"
    

    Hope this helps