user1797770
user1797770

Reputation: 159

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, "");

Upvotes: 0

Views: 673

Answers (5)

Tim Down
Tim Down

Reputation: 324497

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 = "";
    }
}

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108480

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()
}

Upvotes: 1

Aaron Lee
Aaron Lee

Reputation: 362

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()});​

Upvotes: 0

Shahzeb Khan
Shahzeb Khan

Reputation: 3642

var str = "yourString"
str = str.substring(1,str.length-1)

Upvotes: -1

Asad Saeeduddin
Asad Saeeduddin

Reputation: 46628

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/

Upvotes: 0

Related Questions