Toon posts:

[Safari/JavaScript] geselecteerde text uit input opvragen

Pagina: 1
Acties:

Verwijderd

Topicstarter
Met onderstaand script wil ik een geslecteerd stukje tekst uit een input of textarea opvragen. Voor IE en Mozilla heb ik het aan de praat alleen safari zorgt voor hoofdbrekens.

Het lijkt erop dat je met window.getSelection() alleen tekst die "op de pagina" staat kunt uitlezen (als je de dummy tekst boven de input selecteerd krijg je die in Safari wel terug).

Vraag is dus: kan ik op de één of andere manier met JavaScript een geselecteerd stukje tekst uit een input/textarea ophalen?

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<html>
<head>
    <script language="JavaScript">
    var TextvalueObj
    
    function getsel()
    {
        if(document.selection)
        {
            //IE - PC
            selObject = document.selection.createRange();
            theSelection = selObject.text;
        }
        else if(TextvalueObj.selectionStart || TextvalueObj.selectionStart == '0')
        {
            //Mozilla/Netscape - PC & Mac
            TextvalueObj.focus();
            startPos = TextvalueObj.selectionStart;
            endPos = TextvalueObj.selectionEnd;
            theSelection = TextvalueObj.value.substring(startPos, endPos)
        }
        else if(window.getSelection)
        {
            //Safari - not working :(
            theSelection = window.getSelection()
        }
        
        alert(theSelection)
    }
    </script> 
</head>

<body>
<form>

    test test test<br>
    <input type="text" value="blaat" name="zzz" onFocus="TextvalueObj=this"><br>
    <input type="button" onMouseDown="getsel()" value="Toon selectie"><br>

</form>
</body>
</html>