开发者

Select a text after alert

I'm testing a syntax for an email input. And it is alerting some messag开发者_运维技巧e on the web browser if the email syntax is wrong. After the user clicks ok on that messsage I want the browser to select the text.

var input = document.createElement('input');
document.body.appendChild(input);
input.onblur = function(){
    var reg = /^([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(this.value) == false){
        alert('Wrong syntax on e-mail');
        $(this).select();//This doesn't work!
    }
}


Interesting issue, it looks like a security-feature. Keep in mind that your script blocks the UI as long as you didn't type a accepted email-adress.

This works for me:

input.onblur = function(){
    var _this=this;
    var reg = /^([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(this.value) == false){
        alert('Wrong syntax on e-mail');
        setTimeout(function(){_this.select();},1)
    }
}

As you see it uses a timeout, but I don't think that the delayed call is the key, the important thing is the different scope where the function will be executed now(scope is now window instead of the input).


Try this

var input = document.createElement('input');
document.body.appendChild(input);
input.onblur = function(){
    var reg = /^([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(this.value) == false){
        alert('Wrong syntax on e-mail');
        SelectText(this);
    }
} 

function SelectText(text) {

    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜