Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting select value has no effect on keyboard use

Tags:

jquery

I have a select with f.e. 10 options ('one', 'two', 'three', ...). Loading the page the first option 'one' is selected.

Within a function I set to fifth option

$("myselect").val('five');

In fact now fifths option is shown in select and value also is set correct.

But now I tab on in my form until I reach this select. And if I now use keyboard down key, the select jumps to option 'two' and not 'six'.

How to set a selected option which works for a later keyboard use, too?

like image 753
Fabian Knauf Avatar asked Nov 08 '12 18:11

Fabian Knauf


1 Answers

Try setting the selectedIndex property. See below,

$('#myselect').val("5").prop('selectedIndex', 4);

DEMO: http://jsfiddle.net/kLZ7z/

Another better cleaner approach is

var nValue = "5";
$('option', '#myselect').filter(function () {        
    return this.value == nValue;
}).prop('selected', true);

DEMO: http://jsfiddle.net/kLZ7z/2/

like image 77
Selvakumar Arumugam Avatar answered Jan 02 '23 11:01

Selvakumar Arumugam