Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<select> window not updating after change in selected attribute in <option>

The sign up form I'm creating has Business and Residential option in select dropdown.

Based on the active page type, I change the default selected option.

Here's the html:

<select class="type_c" name="type_c">  // default selected is business
    <option value="Business" selected="selected">Business</option>
    <option value="Residential">Residential</option>
</select>

Here's the code I run in the footer of every page to change those values:

$(function(){

    var pageType = getPageType(); // returns either 'Business' or 'Residential'

    $('.type_c option').each(function(){
        $(this).removeAttr('selected');
    });

    $('.type_c option').each(function(){
        if($(this).html() == pageType)
            $(this).attr('selected','selected')
    });

});

The issue is that when it's on a 'Residential' page, the 'Residential' option is selected in DOM but visually, the 'Business' option is selected!

Thanks.

like image 529
MonOve Avatar asked May 18 '12 17:05

MonOve


People also ask

How do I change selected option in select tag?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.

How do I preselect a select option?

Learn HTML A select box also called drop down box provides an option to list down various options in the form of drop down list. You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.

How do I change selection options in HTML?

We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked. We get the 2 buttons with getElementById .


1 Answers

Sine this is changing the attribute after the initial value, it is technically a property, and you should use $(this).prop() instead of $(this).attr().

Also, try setting the value to true instead of selected

$(this).prop('selected',true);

Alternatively, you could also set the value of the select element:

$('.type_c').val(pageType);

like image 101
Tom Pietrosanti Avatar answered Sep 29 '22 00:09

Tom Pietrosanti