עריכת טקסט מסומן מ-textarea

‏ • 26 ביולי, 2004

לא פעם קורה שאנחנו רוצים לאפשר למשתמש באתר (במסגרת הודעות בפורומים וכדומה)
לעצב את הטקסט הנשלח. יש לנו כמה אפשרויות כדי לבצע את זה:

1) להשתמש בדרך הפשוטה של הוספת תג פותח בסוף ה-textarea (ע"י לחיצה על כפתור)
שהמשתמש יכניס טקסט ושיסגור את התג ע"י לחיצה על כפתור נוסף. כך תיראה הפונקציה:











1
2
3  








function addTags(tag,textAreaId){
         document.getElementById(textAreaId+""),value+=tag
}



יתרון: פשוט ועובד בכל הדפדפנים בלי שינוי בקוד.
חיסרון: יכול להיות שהמשתמש לא יסגור תגיות .


2) שימוש באובייקט ה-Selection של IE ובשלושה תכונות של textarea הנתמכות רק
במוזילה(NS6 ומעלה). ע"י שימוש בנ"ל אנו יכולים לתת למשתמש אפשרות לסמן טקסט
מסויים ואז לעטוף אותו בתגיות העיצוב שהמשתמש בחר או שהמשתמש פשוט יכתוב בין
תגית הפתיחה והסגירה שהוספנו אוטומטית ל-textarea.
הפונקציה תיראה כך:











1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24  








function addtoForm(openTag, closeTag, textAreaId){ /// Add tags code to textarea
    var txtAr = document.getElementById(""+textAreaId), oRange
    txtAr.focus()
    if (document.selection && document.selection.createRange){
        oRange=document.selection.createRange(); /// Create Range object form the selected Text
        if (oRange.parentElement()==txtAr){ /// Check if the parent of the Range object is our textarea
         oRange.text= openTag+oRange.text+closeTag /// add the tags before and after the selected text
        }
    }else if(navigator.appName=="Netscape"){
        var txtLength = parseInt(txtAr.textLength) // fint the length of the selected text
        var selStart=txtAr.selectionStart /// find the start position
        var selEnd=txtAr.selectionEnd /// find the end position
        if (selEnd==2 || selEnd==1){
            selEnd=txtLength
        }
        var sect1 = (txtAr.value).substring(0,selStart) /// text before the selected text
        var sect2 = (txtAr.value).substring(selStart,selEnd) // the selected text
        var sect3 = (txtAr.value).substring(selEnd,txtLength) /// text after the selected text
        txtAr.value = sect1+openTag+sect2+closeTag+sect3 /// add the tags before and after the selected text
        txtAr.focus()
    }else{
        return (alert("your browser is not supported by us only Mozilla(NS6 & higher) AND IEn thanks"),false)
    }
}


בהצלחה!

תגיות: , , ,

ניר טייב

בונה אתרים ומתכנת בשפות:HTML, CSS, JavaScript, PHP 5, JSP&Servlets ורובי.

תגובות בפייסבוק