JQuery :delegate select of of does not work
- 2020-03-30 01:28:44
- OfStack
JQuery has a handy delegate feature that binds an event handler to current and future (dynamically added) elements.
For example, after dynamically adding an input text box, I want all text boxes (whether dynamically added or not) to be capitalized automatically when they get focus.
<!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 boxes
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 a little feature that will let the text box be selected automatically when I get focus.
$().ready(function(){
$("#ulTarget").delegate(":text","focus",function(){
$(this).val($(this).val().toUpperCase()).select();
});
})
However, in practice,.select() does not work, but setTimeout
$().ready(function(){
$("#ulTarget").delegate(":text","focus",function(){
var jqObj = $(this);
jqObj.val(jqObj.val().toUpperCase());
setTimeout(function(){jqObj.select();},100);
});
})
Resolved.