[C#] ASP.NET Client ID 로 문자 전체 선택하는 스크립트.
2015. 9. 9. 14:35ㆍCoders
이 예제는 Postback 이후에 특정 영역의 텍스트를 모두 선택할 때 삽입해야 할 스크립트를 생성하는 메서드 입니다. 만약 단순 스크립트만 사용할 거면, 그냥 아래 소스에서 문자열만 뽑아서 js 형태로 만들면 됩니다.
소스 나갑니다.
/// <summary> /// 전체선택 스크립트 생성 /// </summary> /// <param name="clientID"></param> /// <returns></returns> public static string CreateSelectAllTextScript(string clientID) { System.Text.StringBuilder sbSelectText = new System.Text.StringBuilder(); sbSelectText.AppendLine("var doc = document;"); sbSelectText.AppendFormat("var text = doc.getElementById('{0}');", clientID); sbSelectText.AppendLine(); sbSelectText.AppendLine("var range;"); sbSelectText.AppendLine("var selection;"); sbSelectText.AppendLine("if (doc.body.createTextRange)"); sbSelectText.AppendLine("{"); sbSelectText.AppendLine(" range = document.body.createTextRange();"); sbSelectText.AppendLine(" range.moveToElementText(text);"); sbSelectText.AppendLine(" range.select();"); sbSelectText.AppendLine("}"); sbSelectText.AppendLine("else if (window.getSelection)"); sbSelectText.AppendLine("{"); sbSelectText.AppendLine(" selection = window.getSelection();"); sbSelectText.AppendLine(" range = document.createRange();"); sbSelectText.AppendLine(" range.selectNodeContents(text);"); sbSelectText.AppendLine(" selection.removeAllRanges();"); sbSelectText.AppendLine(" selection.addRange(range);"); sbSelectText.AppendLine("}"); return sbSelectText.ToString(); }
그런데, UpdatePanel 내의 컨트롤에 사용 시, 간혹 ScriptManager 가 안 먹는 경우가 있습니다. 그럴 경우 다음과 같이 코드를 작성하면 정상 작동합니다.
ScriptManager.RegisterStartupScript( this.yourUpdatePanel, this.yourUpdatePanel.GetType(), this.yourUpdatePanel.ClientID, CreateSelectAllTextScript(this.yourControl.ClientID), true);
그런데(2), 희한하게, StringBuilder 로 스크립트를 생성하는 시점에 앞 뒤를 <script> 태그로 감싸니 작동을 안 하네요. 그 이유가 뭔지는 잘 모르겠습니다. 음.
즐거운 코딩 생활 되세요.
'Coders' 카테고리의 다른 글
[MSSQL] INSERT/UPDATE 문에서 값 사용하기 (0) | 2015.09.14 |
---|---|
[C#] ClosedXML, Spire.XLS 무료 버전 사용 시 AutoFitColumns 버그 (0) | 2015.08.12 |
[C#] 스플리터를 스무스(?)하게 접기 (0) | 2015.06.10 |