Search code examples
javascripthtmldomdom-eventsonchange

How is setting the selectedindex of a select element different from selecting one item with a mouse?


In a html page, if I use my mouse to select an item from a drop-down list(the select and option html elements), then the onchange event will be fired. But if I use Javascript to change the selectedindex of a select element, then the onchange event won't be fired.

How are those two actions different?

How can I trigger the onchange event (not by calling selectElement.onchange() explicitly)?


Solution

  • See this: http://jsfiddle.net/9xe9b/

    $("#currency").change(function(){
        var val = $(this).val();
    
        $(this).val(formatCurrency(val));
    });
    
    $("#infinite").change(function(){
        var val = $(this).val();
    
        $(this).val(formatCurrency(val));
        $(this).change(); // simulate the change event. 
    });
    
    function formatCurrency(num) {
        num = isNaN(num) || num === '' || num === null ? 0.00 : num;
        return parseFloat(num).toFixed(2);
    }
    

    If you enter a value into the second textbox and pop open your console, you'll see this error: Uncaught RangeError: Maximum call stack size exceeded

    This is what we would have to worry about if changing a value in javascript caused a related event to fire. Infinite loops!

    So, if you need to repeat functionality when changing a value through the UI or through javascript, you should create a function that does what you want and call it in the appropriate instances.