开发者

How to select all value text when a dijit.form.TextBox or similar widget is focused

I am searching a way that when a dijit.form.TextBox or extended / similar widget ( such as NumberTextBox, CurrencyTextBox ) is focused, select all text in it's input DOM Node.

The following node seems to be not working:

<input type="text" id="widget" dojoType="dijit.form.TextBox" value="a value" />
<script type="text/javascript">
dojo.connect( dijit.byId('widget'), 'onFocus', function开发者_运维知识库() {
    this.textbox.select();
});
</script>


If you're using Dojo 1.4 or higher, there's already a property for this on the TextBox, called selectOnClick - just set that to true and it should do what you want.

This may actually be partly why your code wasn't working, because technically you seem to be using widget events properly - except that this is probably not what you want it to be, the way you connected the event.


I've found that selectOnClick doesn't always help, because sometimes a field obtains focus without the user mouse-clicking into it.

Instead you can use this:

dijit.byId("widgetId").attr("onFocus", function() { this.focusNode.select(); });

NOTE: focusNode may not be available for all widgets. Each may have its own custom way of referencing the INPUT element. It's not documented for a FilteringSelect widget, but it works just fine for me.


There are a few things preventing this form working correctly.

Firstly, dijit.byId('widget') will select the Dojo widget (dijit) object and not the DOM object. The events and available methods on this are NOT the same as the underlying DOM object. dojo.byId(), on the other hand, selects the DOM element.

Secondly, "onFocus" will not target the DOM event. DOM events need to be all in lowercase, so in this situation you would use "onfocus".

Try this code:

dojo.connect( dojo.byId('widget'), 'onfocus', function() {
    dojo.byId('widget').select();
});

That should allow it to work correctly. I replaced the this.textbox.select() since I can't see any reference to an object that 'this' would be referencing.

Try it here


Since Dojo 1.7:

require(["dojo/on", "dojo/dom"], function(on, dom){

    //direct domNode id method
    on( dom.byId('widget'), 'focus', function() {
        dom.byId('widget').select();
    });

    //via programmatic widget reference
    on( myWidgetReference.focusNode, 'focus', function() {
        myWidgetReference.focusNode.select();
    });

});

Note: GreenWebDev's note still stands (re: focusNode availability)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜