JQuery: the solution to select () in delegate that does not work (example)

Source: Internet
Author: User

JQuery has a very useful delegate function, which can bind an event handler function to the current and future (dynamically added) elements.

For example, in the following example, after dynamically adding an input text box, I want all text boxes (whether or not they are dynamically added) to be automatically converted to uppercase when getting the focus.
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> delegate test </title>
<Script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.js"> </script>
<Style type = "text/css">
* {Padding: 0; margin: 0; list-style: none; margin: 5px}
</Style>

<Script type = "text/javascript">
// Dynamically add a line of text input box
Function addInput (){
$ ("# UlTarget"). append ("<li> <input type = \" text \ "value = \" aaaaaa \ "/> </li> ");
}


$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
$ (This). val ($ (this). val (). toUpperCase ());
});
})
</Script>
</Head>
<Body>
<Ul id = "ulTarget">
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
<Li> <input type = "text" value = "123456abc"/> </li>
</Ul>
<Button id = "btnAdd" onclick = "addInput ()"> add input </button>
</Body>
</Html>

Next, I want to add some small functions. When getting the focus, I also want the text box to be automatically selected.
Copy codeThe Code is as follows:
$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
$ (This). val ($ (this). val (). toUpperCase (). select ();
});
})

However, in actual tests,. select () does not work.
Copy codeThe Code is as follows:
$ (). Ready (function (){
$ ("# UlTarget"). delegate (": text", "focus", function (){
Var jqObj = $ (this );
JqObj. val (jqObj. val (). toUpperCase ());
SetTimeout (function () {jqObj. select () ;},100 );
});
})

Solved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.