简体   繁体   中英

Delete char from input using start and end position javascript

I am trying to delete text from input on a following way, and its not working in Mozilla, can anyone help?
In IE its working fine.

var start = txt.selectionStart;
var end = txt.selectionEnd;  
var selectedStr = txt.value.toString().substring(start, end);
txt.value = txt.value.toString().replace(selectedStr, "");

Mozilla (and other browsers) have a different implementations using document.selection , window.getSelection() so you'll need to adjust you code according to those methods/properties and legacy support table. You can use many libs out there that normalizes this for you.

Here is a code example that works in webkit:

var selectedStr = '';
if (window.getSelection) {
    var selectedText = window.getSelection().toString()
}

It looks as though you're trying to delete the selected text in a text input. You'll need two different approaches: one for IE < 9 and and one for other browsers that support selectionStart and selectionEnd properties. Here's how:

Demo: http://jsfiddle.net/hwG7f/1/

Code:

function deleteSelected(input) {
    input.focus();
    if (typeof input.selectionStart == "number") {
        var start = input.selectionStart,
            end = input.selectionEnd,
            val = input.value;
        if (start != end) {
            input.value = val.slice(0, start) + val.slice(end);
            input.setSelectionRange(start, start);
        }
    } else if (typeof document.selection != "undefined") {
        document.selection.createRange().text = "";
    }
}

Replacing the value isn't the correct way to approach this. Try taking the chunk of string preceding and following the selection:

var start = txt.selectionStart;
var end = txt.selectionEnd;
txt.value = txt.value.substring(0,start) + txt.value.substring(end);

Here is a demonstration: http://jsfiddle.net/BuMUu/1/

SelectionStart only works in IE9+.

Sorry, but why don't you just directly set it to "".


<input type="text" id="txt" />
<input type="button" value="Clear" id="clear" />​

function clear() {
    var txt = document.getElementById('txt');
    txt.value = "";
}
$('#clear').click(function(){clear()});​
var str = "yourString"
str = str.substring(1,str.length-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM