Reputation: 159
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
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
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
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
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