javascripthtml-selectmootools

Setting a Select Option Value to a Variable


Is it possible to set the value of a Select Option equal to a predefined variable, then use its method? Here's an example:

<select class='hidden' id='teamChoice' onchange='chooseTeam()'>
<option value="" selected>What team</option>
    <option value='bostonCeltics'>Boston Celtics</option>
</select>


var bostonCeltics = {
    conferencePA: "5=Conference=Eastern",
    divisionPA: "5=Division=Atlantic"
}

function chooseTeam() {
    switch ($('teamChoice').selectedIndex) {
        case 0:
            break;
        case 1:
            $('PAType=Name=Value3').innerHTML = this.conferencePA;
            break;
    }
}

Ideally, on selecting the option titled Boston Celtics, I could use a method to access the different properties of the variable object bostonCeltics. Is this possible?


Solution

  • I'm not a Mootools user, but I think I understand what you're getting at, and believe I can point you in the right direction.

    In Javascript, you can access any object property directory, OR by using array notation. In other words, given foo = { bar: 1, baz: 2 }, the following are equivalent:

    console.log( foo.bar );      // prints 1
    console.log( foo["bar"] );   // prints 1
    var s = "bar";
    console.log( foo[s] );       // prints 1
    

    Things get trickier because you define bostonCeltics as a var, meaning it's not necessarily a property of any object. You can still accomplish what you want with eval, though the use of eval is discouraged:

    var s = "bostonCeltics";
    console.log( eval( s + ".conferencePA" ) );    // prints "5=Conference=Eastern"
    

    Personally, I would move bostonCeltics into a parent object, and use the array notation to access its properties, then what you want to do is pretty straightforward. To wit:

    var teams = {
        bostonCeltics = {
            conferencePA: "5=Conference=Eastern",
            divisionPA: "5=Division=Atlantic"
        }       
        // more teams go here
    }
    
    function chooseTeam() {
        var tc = $('teamChoice');
        var val = tc[tc.selectedIndex].value;
        console.log( teams[val].conferencePA );    // prints "5=Conference=Eastern"
    }
    

    Here's a jsFiddle of this in action: http://jsfiddle.net/sQvBZ/

    I hope this gets to the heart of what you're asking.