22

Possible Duplicate:
Check checkbox checked property using jQuery

Can anyone let me know how to check the value is selected in the html textbox using jquery. For example the value in the textbox if selected the text is slected with blue background.

Community
  • 1
  • 1
teenu
  • 684
  • 2
  • 8
  • 24
  • Can you expand on this a bit? Its a bit unclear at the moment. What have you tried so far? – Gaz Winter Dec 19 '12 at 09:35
  • 1
    @zerkms he is after textbox though not checkbox, unless I am reading this wrong. – Gaz Winter Dec 19 '12 at 09:36
  • 1
    @Zerkms, he is asking for selected text inside a textbox. (I guess) – XCS Dec 19 '12 at 09:36
  • 1
    Hm... Why does the background's color matter anyway? :-" – XCS Dec 19 '12 at 09:37
  • @GazWinter : I mean the textbox. the color is just to make understand its not a select or a radio button. Got commond to select commond like window.selected() for outside the textbox but I am looking something which can get the selected value in the textbox. Please Help. – teenu Dec 19 '12 at 09:42

1 Answers1

9

See this : http://jsfiddle.net/rT5vR/

var t = '';
if(window.getSelection) {
    t = window.getSelection();
} else if(document.getSelection) {
    t = document.getSelection();
} else if(document.selection) {
    t = document.selection.createRange().text;
}
return t;
}

$("#myElement").select(function(eventObject) {
alert(getSelected().toString());
});

​Or

$('#myElement').select(function(e) {
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
alert($('#myElement').val().substring(start, end));
});

The second one is perfect. Don't know how much cross-browser the first one is... ​

Anujith
  • 9,370
  • 6
  • 33
  • 48