Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Javascript function from html select

I have a simple html select tag with some options attached:

<select>
<option>school a</option>
<option>school b</option>
<option>school c</option>
</select>

I'd like to attach some simple event handlers to the options the same way I would to say... a link:

<option onclick="scheduleA();">school a</option>

Do I need to construct a separate Javascript function to deal with event handling in this situation or is there some quick html that will accomplish this task?

like image 885
kjarsenal Avatar asked Feb 12 '12 20:02

kjarsenal


People also ask

How do you call a JavaScript function from HTML?

Calling a function using external JavaScript file Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How do you execute a JavaScript function?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

How can call JavaScript function without button click in HTML?

Have you tried the setInterval() javascript function? It will automatically execute your code in a specified time(in milliseconds). setInterval( [you code or function call][, time interval in milliseconds] );

How do you call a function button in HTML?

Call a JavaScript function from an HTML button click event getElementById() method. Now once you click on the button, the test() function will be executed and the alert box will be displayed in the browser.


2 Answers

You would be better off assigning onChange="schedule(this.value); on the <select>. Partly because it actually works, partly to avoid redundant code if the same option is selected twice, partly because fewer event handlers is always better.

like image 130
Niet the Dark Absol Avatar answered Oct 02 '22 19:10

Niet the Dark Absol


Use an onchange event on the select

<select onchange="scheduleA.call(this, event)">

Then in your handler...

function scheduleA(event) {
    alert(this.options[this.selectedIndex].text);
}

DEMO: http://jsfiddle.net/hYY6X/

like image 21
user1106925 Avatar answered Oct 02 '22 19:10

user1106925