Reputation: 13850
I'm testing a syntax for an email input. And it is alerting some message 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!
}
}
Upvotes: 1
Views: 879
Reputation: 117334
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).
Upvotes: 4
Reputation: 69915
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);
}
}
Upvotes: 0