Duncan Mackie
Duncan Mackie

Reputation: 21

Select attribute not getting set

None of these set the value to contain the word selected. This means that when the select list gets passed back to php the selection become 'undone':

 jQuery("#tag_photo2").val("<?php echo $pg->m2; ?>").attr("selected",true);
    jQuery("#tag_photo2").val("<?php echo $pg->m2; ?>").attr('selected','selected');
    jQuery("#tag_photo2").val("<?php echo $pg->m2; ?>").prop("selected",true);

The following shows that the selection is actually known:

jQuery("#value2").html($("#tag_photo2 :selected").text() + " (VALUE: " + $("#tag_photo2").val() + ")");

as I get 'CURRENT SELECTED: test123 (VALUE: 2)' displayed.

The selection here is correct, but if sent to php it get lost.

Tried with jQuery 1.8.2 and 1.7.1, Firefox 15.0.1 and Chrome 22.0.1229.94.

Have searched around and can't find any other ways to set the 'selected' word in the value field of an option.

Any ideas how to make this work?

Upvotes: 2

Views: 559

Answers (1)

Maktouch
Maktouch

Reputation: 3247

Try .prop instead of .attr

$("#selectIDGoesHere > option[value='valueOfTheOptionHere']").prop("selected", true);
jQuery('#tag_photo1 > option[value="2"]').prop('selected',true)

Also, if you're using any plugins that skins the select like Chosen or Select2, you have to refresh them.

Upvotes: 1

Related Questions