1

I'm trying to add an onChange event on an select element. The html looks like this:

<select name="to" onChange="if(type(this.selectedIndex) != undefined){ alert('hello'); }">
    <option value="newsletter">Alle nieuwsbrief-abonnees</option>
    <option value="customer_all">Alle klanten</option>
    <option value="customer_group">Klantengroep</option>
    <option value="customer">Klanten</option>
    <option value="affiliate_all">Alle affiliates</option>
    <option value="affiliate">Affiliates</option>
    <option value="product">Producten</option>
    <option value="marketing">Alle Marketing Abbonnees</option>
    <option value="marketing_all">Alle Marketing</option>
    <option value="subscriber">Alle Nieuwsbrief Abbonnees &amp; Marketing Abbonnees</option>
    <option value="all">Alle Klanten &amp; Marketing</option>
    <option value="old_brian">Oude lijst Brian</option>
    <option value="old_dunamis">Oude lijst Dunamis</option>
    <option value="old_frohlich">Oude lijst Frohlich</option>
    <option value="old_gaithers">Oude lijst Gaithers</option>
    <option value="old_gospel7">Oude lijst Gospel7</option>
    <option value="old_lifeshop">Oude lijst Lifeshop</option>
    <option value="old_meyer">Oude lijst Meyer</option>
    <option value="old_opwekking">Oude lijst Opwekking</option>
    <option value="old_pelgrim_kerken">Oude lijst Perlgim Kerken</option>
    <option value="old_pelgrim_klanten">Oude lijst Pelgrim Klanten</option>
    <option value="old_pelgrim_pers">Oude lijst Pelgrim Pers</option>
    <option value="old_pelgrim_scholen">Oude lijst Pelgrim Scholen</option>
    <option value="old_test">Oude lijsten test</option>
</select>

Here's an JSFIDDLE of it

The onchange script came from an answer on stackoverflow: Is there an onSelect event or equivalent for HTML ?

But i get the following error:

Uncaught TypeError: string is not a function 

I'm clueless, what's the problem? Can't you do an if statement in an onChange event? Or is it something else?

Community
  • 1
  • 1
Mathlight
  • 6,436
  • 17
  • 62
  • 107

1 Answers1

6

type is not a built-in function. typeof is an operator, though, that may be what you wanted; it returns a string:

if (typeof this.selectedIndex !== "undefined") // But see below

But note that selectedIndex is never undefined on select elements. It may be -1, to indicate no selection, but not undefined. So:

if (this.selectedIndex !== -1)

Regarding the error: My guess is that you have a global variable called type, and that it contains a string. That would give you the error TypeError: string is not a function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you sir, that did it. the typeof was indeed the fix. Now using the second recomendation. Will accept when the time has come. Thanks again :D – Mathlight Jul 29 '13 at 16:46
  • 1
    @Mathlight Sorry for the confusion I've caused, and thanks for T.J Crowder for the correction! – K Z Jul 29 '13 at 20:53