0

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');
});
1
  • Where do you append the input? Commented Mar 20, 2013 at 1:04

2 Answers 2

1

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 () {
Sign up to request clarification or add additional context in comments.

4 Comments

error display: Error: Unable to get value of the property 'handler': object is null or undefined
@JinYong Which version of jQuery are you using?
jQuery JavaScript Library v1.4.2
Check the edit @JinYong This will work with 1.4.2 I would recommend to upgrade though.
0

If you want to add handlers to dynamically created content, you'll want to either add the handler after the content has been added or, more commonly done, just use event delegation. For jQuery, this means using .on:

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

Here's the documentation to learn more about using .on.

2 Comments

i tried but error display Error: Object doesn't support property or method 'on'
If you're using an old version of jQuery, then use .live instead of .on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.