Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an onSelect event or equivalent for HTML <select>?

People also ask

What is the HTML code for select?

<select>: The HTML Select element.

What are the 3 types of selecting a HTML element?

Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)

When user makes a selection in the HTML select list event is raised?

When user makes a selection in the HTML select list, on cho vent is raised. 3. The property for an ID is referred to by. operator.


Here is the simplest way:

<select name="ab" onchange="if (this.selectedIndex) doSomething();">
    <option value="-1">--</option>
    <option value="1">option 1</option> 
    <option value="2">option 2</option>
    <option value="3">option 3</option>
</select>

Works both with mouse selection and keyboard Up/Down keys whes select is focused.


I needed something exactly the same. This is what worked for me:

<select onchange="doSomething();" onfocus="this.selectedIndex = -1;">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Supports this:

when the user selects any option, possibly the same one again


I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.

If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.

I assigned my dropdown an ID, selected, and used the following:

$(function () {
    $("#selected").live("change", function () {

    // do whatever you need to do

    // you want the element to lose focus immediately
    // this is key to get this working.
    $('#selected').blur();
    });
});

I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.

http://api.jquery.com/live/

Edit: Use the on selector as opposed to .live. See jQuery .on()


Just an idea, but is it possible to put an onclick on each of the <option> elements?

<select>
  <option onclick="doSomething(this);">A</option>
  <option onclick="doSomething(this);">B</option>
  <option onclick="doSomething(this);">C</option>
</select>

Another option could be to use onblur on the select. This will fire anytime the user clicks away from the select. At this point you could determine what option was selected. To have this even trigger at the correct time, the onclick of the option's could blur the field (make something else active or just .blur() in jQuery).