2

Is there any alternative method for the following code in jquery or javascript.?

function isTextSelected(input) {
  if (typeof input.selectionStart == "number") {
    return input.selectionStart == 0 && input.selectionEnd == input.value.length;
  } else if (typeof document.selection != "undefined") {
    input.focus();
    return document.selection.createRange().text == input.value;
  }
}
<input id="text_selected" type="text" value="Select Text" />
<input onmousedown="console.log(isTextSelected(document.getElementById('text_selected')));" type="button" value="Selected or Not" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Abhii
  • 295
  • 2
  • 6
  • 18

3 Answers3

1

I'm unsure where you get the isTextSelected() method but perhaps you should look into Window.getSelection(): https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

Perhaps this will help too: How to get selected html text with javascript?

Community
  • 1
  • 1
Mike Sav
  • 14,805
  • 31
  • 98
  • 143
1

If you just need to see if it is empty or changed:

var field = document.getElementById('text_selected'); 
if (field.value=="" || field.value==field.defaultValue) {
  alert("empty or not changed");
}

You can add trim:

if (field.value.trim()=="" 

Or using jQuery:

if ($.trim(field.value)=="" 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

if you mean get selected text from drop down list you can use this :

$("#yourdropdownid option:selected").text();
Hasan Daghash
  • 1,681
  • 1
  • 17
  • 29