Search code examples
javascriptjqueryonfocusjquery-1.4

focus() not working for input that created by javascript


I have create a html page by using javascript to create the input box, and using jquery to assign the class to the input box then trying to using focus() by using the class name, but it's not working at all. When I click on the input box, alert is not pop up :(

Does anyone know what is going wrong here ? and how can I fix this issue?

html page:

  <table border="0" width="800">
    <tr>
        <td align="center">
            <div id="test">

            </div>       
        </td>
    </tr>
  </table>

javascript:

htmlValue = "<input maxlength='4' size='2' type='text'  id='startTime_1' value='" + startTime + "'  />";

$("#test").html(htmlValue );


$('#startTime_1').addClass('test1');


$('#test1').focus(function () {
    alert('inside');
});

Solution

  • The following code:

    $('.test1').focus(function () {
        alert('inside');
    });
    

    should instead be bound to #test first.

    $('#test').focus('.test1', function () {
        alert('inside');
    });
    

    Since you are still using jQuery 1.4.2; you need to use .live() method for handlers.

    The code shall be

    $('#test').live('focus', '.test1', function () {