سؤال

I have a jquery script which enables to copy selected text in desirable field with click on corresponding button... Now I need to restrict those inputs id different amount of characters... First input should have max of 5 characters, second max of 2 and third max of 3.... I tried to limit it with maxlength="number" it worked on manual input or copy and paste in the old fashion way but ignored that copy on button click... I suppose that this is needed to solved wit something in that getSelection(); function? Or something else?

Here is current jsfiddle: http://jsfiddle.net/dzorz/ZhN3M/

try to select a part of text and then click on one button to test functionality

html:

<p id="highlighted_text">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="input3"> <a href="#" id="copy3" class="btn btn-primary">Copy to 3</a>

</div>
</fieldset>
</form>

script:

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());
});
});
هل كانت مفيدة؟

المحلول

not sure if i got what you are saying but assuming this is what you want

used selected's toString method to convert the selected characters to string ..and used substring to get first n characters

$(document).ready(function () {

    $('#copy1').click(function () {
       var selectedText = getSelectedText().toString();
       $('#input1').val(selectedText.substring(0, 5));
    });
    $('#copy2').click(function () {
       var selectedText = getSelectedText().toString();
       $('#input2').val(selectedText.substring(0, 2));
    });
    $('#copy3').click(function () {
      var selectedText = getSelectedText().toString();
      $('#input3').val(selectedText.substring(0, 3));
    });
});

fiddle here

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top