May 9, 2013

how to get click event of text box with in an li using jquery

Anoop’s Questions:

I have a list of text box within <li>'s. How can I get the click event of the text box?

They are placed inside a <div> nested as shown below.
the lis’s section is dynamically created with jquery .. but the click event is not triggerd as like . i have tried the jquery answers posted in dynamic

<div>
   <ul>
        <li><input type="text"></li>
        <li><input type="text"></li>
    </ul>
</div>

Thanks

$('li').on('click','input[type="text"]', function(){
//code goes here//
});

There you go.

jQuery selectors are similar to CSS Selectors. You can use the same pattern and apply event handler to the elements. But, It would be very easy if you identify your code using class and id. Like

<div id="mydiv">
<!-- Adding ID to the div like this will help you to target your event handler
     To a set of required elements only -->

   <ul>
        <li><input type="text"></li>
        <li><input type="text"></li>
    </ul>
</div>

Then you can catch the click event on the text box very simple as

$("#mydiv input[type='text']").on('click', function() {
// ^ Isn't this as same as CSS?

    console.log("I am clicked");
});

With your markup even though you apply event handler it will be general and will apply to all the text boxes inside a div throughout the page.

If you dont want to change your markup and want to apply the function to all the input boxes. A general version of this code would be:

$("div :text").on('click', function() {
    console.log('I am clicked');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!