sdFRRR
sdFRRR

Reputation: 23

onchange select run function

<select onchange="alert();">
            <option>d</option>
            <option>de</option>
            <option>dewe</option>
            <option>dewee</option>
        </select>

I want the onchange event of a <select> element to display an alert but it's not working.

Any ideas what's wrong?

Upvotes: 2

Views: 2739

Answers (3)

F-A
F-A

Reputation: 643

You should give a string as a parameter in your alert function if you want it to work...

Upvotes: 0

Mark Biek
Mark Biek

Reputation: 150749

I'm assuming your issue is that the alert() call displayed undefined instead of the value of the <select>.

If you want to see the value of the <select>, do this instead:

<select onchange="alert(this.value);">
    <option>d</option>
    <option>de</option>
    <option>dewe</option>
    <option>dewee</option>
</select>

jsfiddle example


Or, if you actually are using jQuery, you can do it like this:

//This is an anonymous function that calls itself with the jQuery object as an argument
//This allows you to use the `$` when making jQuery calls but the code
//will run without modification if jQuery is in noConflict() mode
(function($) {
    //This is the important part
    //Here, we bind to the change event and alert the value
    $('select').change( function(e) {
        alert($(this).val());
    });
})(jQuery)

jsfiddle example 2

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69905

That should work but you can also try this provided you include jQuery on your page

$(function(){

   $("select").change(function(){
      alert($(this).val());
   });
});

Upvotes: 1

Related Questions