Search code examples
javascriptdom-events

How do I change a text link that runs my script to a dropdown link?


I have a JavaScript that changes the output on the same page by using:

<"a href="#" onclick="change('Bob','0','0','2','2','1','0','0')">Bob</a>
<"a href="#" onclick="change('Sam','0','0','2','2','1','0','0')">Sam</a>
<"a href="#" onclick="change('Ted','0','0','2','2','1','0','0')">Ted</a>    

I would like to change the links to a dropdown (select - option) form field.

Any help putting me in the right direction will be appreciated.


Solution

  • <select size="1" onchange="change(this.value, '0','0','2','2','1','0','0')">
        <option>Bob</option>
        <option>Sam</option>
        <option>Ted</option>
    <select>
    

    Using this.value gives you the currently selected option of the select box (Bob, Sam or Ted).


    EDIT

    If you want to pass different parameters to your function, you can do it like this:

    Javascript:

    function selectValueChanged(value){
        switch(value){
            case "Bob":
                change('Bob','-1','0','2','4','6','0','0');
                break;
            case "Sam":
                change('Sam','0','-2','3','5','1','0','2');
                break;
            case "Ted":
                change('Ted','2','1','4','2','3','2','0');
                break;
        }
    }
    

    HTML:

    <select size="1" onchange="selectValueChanged(this.value)">
        <option>Bob</option>
        <option>Sam</option>
        <option>Ted</option>
    <select>
    

    So you pass your selected value to selectValueChanged, and this function calls the change function with the appropriate paremeters.