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.
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.
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With