MorariJan
MorariJan

Reputation: 35

get selected text on button click using javascript?

Basically I am trying to get selected text if a user click on a div.

Code:

$('.boldTextButton').mouseup(function(event){
    var SelectionDetails = getSelectionText();
    console.log(SelectionDetails);
});

function getSelectionText() {
    var text = "", startRange=0, endRange=0;
    if (window.getSelection) {
        text = window.getSelection().toString();
        startRange = window.getSelection().anchorOffset;
        endRange = window.getSelection().focusOffset;
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }

    return [text, endRange, startRange];
}

Unfortunately with above method, when the mouse is clicked, it first de-select the text and then the returned value I get is empty "".

I also have tried event.preventDefault() and event.stopPropegation(), still didn't work.

Upvotes: 1

Views: 655

Answers (1)

Rush.2707
Rush.2707

Reputation: 683

Based on my understanding of your question, I guess you want to show selected text on click of a button. So, simply save selection in a hiddenfield and show from there, this will work.

$('#btnSave').click(function(e){
console.log($("#hdnValue").val());
});

$('.boldTextButton').mouseup(function(event){
    var SelectionDetails = getSelectionText();
    $("#hdnValue").val(SelectionDetails);
});

function getSelectionText() {
    var text = "", startRange=0, endRange=0;
    if (window.getSelection) {
        text = window.getSelection().toString();
        startRange = window.getSelection().anchorOffset;
        endRange = window.getSelection().focusOffset;
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }

    return [text, endRange, startRange];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boldTextButton">
<h2>Sample text 1</h2>
<h2>Sample text 2</h2>
<h2>Sample text 3</h2>
<h2>Sample text 4</h2><h2>Sample text 5</h2>
<h2>Sample text 6</h2>
<h2>Sample text 7</h2><h2>Sample text 8</h2>
<h2>Sample text 9</h2>
<h2>Sample text 10</h2><h2>Sample text 11</h2>
</div>

<div class="btnText">
<input type="hidden" id="hdnValue" />
<input type="button" id="btnSave" value="show" />
</div>

Upvotes: 2

Related Questions