1

I have situation for professionals here, plus I don't have one line of jquery code writen... I have text paragraph and three input fields matched with buttons... My wish is that on selection of text in paragraph you could get this same selection as value in wished input when you click on button copy. I've searched web and did not find something similar to that stuff

I have js fiddle with html only and you could update it: http://jsfiddle.net/dzorz/5DKuY/

HTML:

    <p>
Aliquam eget ipsum accumsan, convallis nulla sit amet, auctor est. 
Nam quis condimentum eros, vel condimentum lacus. In id enim at sem 
gravida sodales eu vitae risus. Morbi sed mi sit amet lectus rhoncus 
gravida a sit amet nisl. Phasellus quis ultricies leo. Duis vel lobortis
mauris. Suspendisse sed diam eu turpis facilisis rutrum vitae vitae
dolor. 
</p>

<form id="myform" class="form-horizontal">
    </fieldset>
        <div class="control-group">
            <input type="text" class="input-small" id="input1">
            <a href="#" id="copy1" class="btn btn-primary">Copy to 1</a>
        </div>
        <div class="control-group">
            <input type="text" class="input-small" id="input2">
            <a href="#" id="copy2" class="btn btn-primary">Copy to 2</a>
        </div>
        <div class="control-group">
        <input type="text" class="input-small" id="input2">
        <a href="#" id="copy2" class="btn btn-primary">Copy to 3</a>
        </div>
    </fieldset>  
</form>

Is that even possible? or it could be solved on somewhat different?

1 Answer 1

2

Something like this might work:

// Get user selection text on page
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

$(document).ready(function () {
    $('#copy1').click(function () {
        $('#input1').val(getSelectedText());
    });
    $('#copy2').click(function () {
        $('#input2').val(getSelectedText());
    });
    $('#copy3').click(function () {
        $('#input3').val(getSelectedText());
    });
});

And the jsfiddler with the working example.

1
  • man! that works! I tried something with range but didn't acomplish it... That's ace! thank you so much! :)
    – dzordz
    Jun 11, 2013 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.