Why isn't .prop("selected",true) not working when .attr() or .addClass() does?

dcp3450 picture dcp3450 · Apr 21, 2014 · Viewed 9.4k times · Source

I have a script that replaces a select box with a set of styled divs by hiding the select box and targeting it when the user clicks a "fake" div. I'm targeting the selected item like this:

targetSelect.eq(optionIndex).prop('selected');

optionIndex is the index of the selected div as it corresponds to the hidden select box option.

The above line does not add "selected" to the target option. I know I'm targeting the correct one since targetSelect.eq(optionIndex).addClass('selected'); will add that class and targetSelect.eq(optionIndex).attr('selected',"true"); sets a selected attribute to true.

I've also tried:

targetSelect.prop('selectedIndex',optionIndex);

but that doesn't work either.

Answer

ReGdYN picture ReGdYN · Apr 21, 2014

I believe this should work:

$('#selectbox option').eq(optionIndex).prop('selected', true);

You could also try this (make sure the optionIndex is not a string!):

targetSelect.val(optionIndex)