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

10,110

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)
Share:
10,110
dcp3450
Author by

dcp3450

Updated on June 17, 2022

Comments

  • dcp3450
    dcp3450 almost 2 years

    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.

  • dcp3450
    dcp3450 about 10 years
    I thought I had the first suggestion before. LOL. Guess not. thanks. I'll mark this as correct once it's unlocked. Thanks.
  • shaedrich
    shaedrich about 3 years
    Thanks for your answer but what does it provide that @ReGdYN's answer didn't already?