Ad

JQuery Removing Set Select Option Selected Not Removing

- 1 answer

I am trying to remove the default selected option in the HTML and set the first as selected, my jQuery seems to be setting the first option as selected fine but it's not appearing selected as it's not removing the original selected option. I have tried 2 methods which are below:

option 1

$('.ty-profile-field__select-state :selected').prop('selected', false);
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

option 2

$('.ty-profile-field__select-state option').each(
    function() {
        $(this).removeAttr('selected');
    }
);
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

option 3

$('.ty-profile-field__select-state').find('option:selected').removeAttr("selected");
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

HTML from source

<select x-autocompletetype="state" id="elm_24" class="ty-profile-field__select-state cm-state cm-location-billing" name="user_data[b_state]">
    <option value="" selected="selected">- Select state -</option>
    <option value="ACT">Australian Capital Territory</option>
    <option value="NSW">New South Wales</option>
    <option value="NT">Northern Territory</option>
    <option value="QLD">Queensland</option>
    <option value="SA">South Australia</option>
    <option value="TAS">Tasmania</option>
    <option value="VIC" selected="">Victoria</option>
    <option value="WA">Western Australia</option>
</select>

You can see it's taking the first option and making selected for not removing the one that is initially set so it's not changing to the first.

Ad

Answer

Turned out what methods i was doing was fine but i needed to wrap in

$(window).load(function(){

As seems the option was being set after i was trying to set it

Ad
source: stackoverflow.com
Ad