When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?
This is what I've attempted, but it doesn't return a bool.
if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) ) ddlCustomerNumber.SelectedIndex = 0;
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
A standard list box is a box containing a list of multiple items, with multiple items visible. A drop-down list is a list in which the selected item is always visible, and the others are visible on demand by clicking a drop-down button.
There are two methods that come to mind:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new ListItem(GetCustomerNumberCookie().ToString()))) { // ... code here }
or modifying your current strategy:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null) { // ... code here }
EDIT: There's also a DropDownList.Items.FindByValue
that works the same way as FindByText, except it searches based on values instead.
That will return an item. Simply change to:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null) ddlCustomerNumber.SelectedIndex = 0;
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