Tuesday, September 29, 2015

JavaScript: Using Select-Option Element (Demo)

Let's go see the HTML stacking:

As you can see, the select is as the parent container of the option elements. And they're wrapped within a paragraph tag.

The first option is disabled and selected so that there'll be no "confusion".

Because this is more about the JavaScript demo, then let's create an output element, using the textarea. So we can see how to capture the value from each option on change event.

The textarea output is wrapped within a div so it will be nicely displayed as block element.
The CSS should be declared in separate style tag. This is for quick example purpose.

From the stacking above, pay attention at the id, class, and value attributes. We'll gonna need those later in our JavaScript (and CSS; for styling them — this topic can be found on another place).


Now the JavaScript:

The above example is an anonymous auto-invoked function.
If you want it to get triggered from some other preceding event(s), you'll need to give a name to the function block, then call it on your custom event(s).


DEMO

Who are you?


All demo codes combined:


Closing

Anyway, the disabled and selected for the first option is optional. It's more formal that way.

The innerHTML is a shortcut method to get the text of each option.
But it can be substituted with an actual attribute. For instance, name or maybe others (data-*, id, etc).
Then use the getAttribute() method to get the value of that particular attribute.

The use of number as the value for each option can also be replaced with strings. Then you need to change the way to get the index of each option.
It's flexible for tinkering.

The cross-browser event for capturing the state-change of this element is change event.
For input event, it works on Chrome (and latest IE — Edge), but not on Firefox (tested just now, later maybe Firefox will update that).


Links

  • Documentation at MSDN.
  • Using optgroup documentation at MSDN.
  • Examples for getting the selected option at W3Schools.

No comments:

Post a Comment

Tell me what you think...