Hi I'm trying to get selected value of a input when input is focused with tab. This is my code,
HTML,
<input id='texteb' type="text" value=''/>
<button>
click
</button>
JS
$(function(){
$(window).on('keyup', function (e) {
var focused = $(':focus');
if (e.which === 9){
var text = focused;
var t = text.value.substring(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
});
});
But I'm getting this error,
TypeError: text.value is undefined
This is Jsfiddle for it.
With answers this issue can be solved with .val() but selectionStart seems to be giving undef
I looked over you fiddle an changed line 6: jsfiddle - modified
//var text = focused;
var text = focused[0];
The reason you were getting undefined
was that you were grabbing a jQuery object (i.e. "focused") that doesn't have those properties (value
, selectionStart
etc.). However, what you really needed was the javascript object, which is available using focused[0]
.
For more methods, check this: How do I pull a native DOM element from a jQuery object? (from: https://learn.jquery.com/)
(ps. I wonder what you are doing with this code?)