Demo: Handling Select List OnChange Event

The form below demonstrates onchange event handling in JavaScript for both select-one and select-multiple type select lists. Select a different size in the select list on the left and the total in the text box will be updated. Click or control-click to add and remove toppings in the select list on the right and these choices will also be reflected in the total.

Demo: Select Lists Onchange

Select Pizza Size and Toppings

Example Form Markup

The HTML markup for the form is displayed here. Notice a hidden input element is used to hold the total for toppings selected.

<form action="#" method="post" id="pizzaForm" class="demoForm">

    <fieldset>
        <legend>Demo: Select Lists Onchange</legend>
        
        <p>Select Pizza Size and Toppings</p>
        
        <p>
            <select name="size" id="size">
                <option value="5">Small: $5</option>
                <option value="8" selected="selected">Medium: $8</option>
                <option value="12">Large: $12</option>
            </select>
            
            <select name="toppings[]" id="toppings" multiple="multiple" size="5">
                <option value=".40">Mushrooms</option>
                <option value=".30">Onions</option>
                <option value=".40">Black Olives</option>
                <option value=".50">Sausage</option>
                <option value=".50">Pepperoni</option>
            </select>
            <input type="hidden" name="toppings_tot" value="0" />
         
            <label>Total: $<input type="text" class="num" name="total" value="8.00" readonly="readonly" /></label>
        </p>
        
    </fieldset>
    
</form>

JavaScript for Handling Select List Onchange Event

The JavaScript for handling selections in both of the lists in the form above is shown here and described below.

// functions assigned to onchange properties
document.getElementById('size').onchange = function() {
    // access form and value properties via this (keyword)
    var form = this.form;
    var total = parseFloat( this.value ) + parseFloat( form.elements['toppings_tot'].value );
    form.elements['total'].value = formatDecimal(total);
};

document.getElementById('toppings').onchange = function() {
    var form = this.form;
    form.elements['toppings_tot'].value = 0; // reset toppings total
    
    // getSelectedOptions function handles select-multiple
    // pass select list (this) and callback function
    getSelectedOptions( this, calcToppingsTotal );
    
    // add toppings total and size price to get total
    var tops_tot = parseFloat( form.elements['toppings_tot'].value );
    var size_price = parseFloat( form.elements['size'].value );
    form.elements['total'].value = formatDecimal(tops_tot + size_price );
};

// called for each selected option, adding its value to toppings total
function calcToppingsTotal(opt) {
    // get reference to hidden toppings total field
    var tot_fld = opt.form.elements['toppings_tot'];
    var val = parseFloat( tot_fld.value );
    // add value of opt to total
    tot_fld.value = val + parseFloat( opt.value );
}

// handles selected options in a select-multiple
function getSelectedOptions(sel, fn) {
    var opts = [], opt;
    
    for (var i=0, len=sel.options.length; i<len; i++) {
        opt = sel.options[i];
        if ( opt.selected ) {
            opts.push(opt);
            if (fn) {
                fn(opt);
            }
        }
    }
    return opts;
}

// format val to n number of decimal places
// modified version of Danny Goodman's (JS Bible)
function formatDecimal(val, n) {
    n = n || 2;
    var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
    while (str.length <= n) {
        str = "0" + str;
    }
    var pt = str.length - n;
    return str.slice(0,pt) + "." + str.slice(pt);
}

A function is assigned to the onchange property of each select list. A function assigned to an event handler property of an object has access to that object inside the function via the this keyword. Both functions assigned to onchange use this: to reference the form containing the select, to reference other elements in the form, and to access the value of the selected option.[1]

Since the values of form elements are always strings, the parseFloat function is used to convert these values to floating point numbers.

The getSelectedOptions function, written to handle multiple selections, is used for the toppings select list with a calcToppingsTotal callback which tallies the total for the toppings selected and places that value in the hidden text field.

Back to top


  1. Find out about other ways to Assign Event Handlers to DOM Elements. ^