Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML define what selection option is active

I have a select box with the following (it has been shortened):

<select id="viewSelector" name="when" style="width:92%;">
    <option value="USA">USA</option>
    <option value="Australia">Australia</option>
    <option value="Germany">Germany</option>
</select>

If the user logs into the control panel and wants to change his country, he gets presented with this form. My problem is that everytime USA is the default and I can not change this depending on the users country. For example, the user lives in Australia. He wants to change his country to USA and goes to this page. I want the country that is displayed to be Australia. Let me know if this makes sense.

like image 218
JustinPGriffen Avatar asked Dec 03 '11 20:12

JustinPGriffen


People also ask

How do you define selected options in HTML?

Definition and UsageThe <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted).

How do I know which option is selected in dropdown?

The selectedIndex property returns the index of the currently selected element in the dropdown list. This index starts from 0 and returns -1 if no option is selected. The options property returns the collection of all the option elements in the <select> dropdown list.

What do you use to get the currently selected option in a select box?

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.


2 Answers

Use the selected attribute of the option tag.

<select id="viewSelector" name="when" style="width:92%;">
    <option value="USA">USA</option>
    <option value="Australia">Australia</option>
    <option selected value="Germany">Germany</option>
</select>
like image 156
Tyilo Avatar answered Oct 21 '22 07:10

Tyilo


To preselect a value, just add the selected attribute to the desired option.

<select id="viewSelector" name="when" style="width:92%;">
    <option value="USA">USA</option>
    <option value="Australia" selected="selected">Australia</option>
    <option value="Germany">Germany</option>
</select>

This will preselect Australia for example.

like image 36
Björn Kaiser Avatar answered Oct 21 '22 07:10

Björn Kaiser