Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - Readonly input box bug in Internet Explorer

I've got a strange bug, well, MSIE does.

Seems it is failing on all major MSIE versions: 6, 7, 8 and 9 (!)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" ><head><title>test</title>

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
  <script type="text/javascript">
   jQuery(document).ready(function(){
    var test=jQuery('#in');
    test.focus(function(){
     if(test.val()=='empty')test.val('');
     test.attr('readonly',false);
    });
    test.blur(function(){
     if(test.val()=='')test.val('empty');
     test.attr('readonly',true);
    });
   });
  </script>

</head><body>

  <input type="text" value="empty" readonly="readonly" id="in"/>

</body></html>

Let me explain how this system works and what is going wrong.

When the user clicks (focuses) the input box, the input box should be made editable (ie, lose readonly flag). Then, when s/he leaves the input box (ie, blur event) some processing is done (not shown in code) and the input box is made readonly.

This works like a charm in most browsers (firefox, opera, webkit-based), but not any version of IE (including 9 beta). The problem is that in IE, the user has to click the input box twice.

At this point, you might ask is the inputbox left readonly the first time? No. I tested it, javascript reports that it is editable.

Easy fix, just fire a click event on the input box (to simulate the user's double click behavior), no? No, .click() and .focus() both failed. No idea why.

Edit: Know that the cursor does show up in the text box, at least visibly.

Important: People, please do at least try the code before answering!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wouldn't say it's a bug. If you change the value, you also remove the current textRange.

Try test.select() , it should give the cursor back to the input.

test.focus()

will result in a loop that will end in an "not enough memory"-error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...