dorado
dorado

Reputation: 1525

addEventListener working in firefox but not in chrome

The given code works in Mozilla Firefox 31.0 but not in Google Chrome 38.0.2125.104 How can this issue be solved?

Please Note : Using the change() function or jQuery is not an option here!

<body>
    <select id="category">
        <option value="movies">Movies</option>
        <option value="artist">Artists</option>
        <option value="authors">Authors</option>
        <option value="chemistry">Chemistry</option>
    </select>
</body>

<script>
window.onload = initialise;
function initialise() {
    var options = document.getElementsByTagName('option');
    for (var i = 0; i < options.length; i++) {
        options[i].addEventListener("click", getQuestion, false);
        //console.log(i);
    }
}

function getQuestion() {
    console.log("getting question..");
}

</script>
</html>

Upvotes: 3

Views: 1732

Answers (2)

CodeGodie
CodeGodie

Reputation: 12132

try this:

<script>
    window.onload = initialise();

    function getQuestion() {
        console.log("getting question..");
    }

    function initialise() {
        var Category = document.getElementById('category');
        Category.addEventListener("change", getQuestion, false);
    }

</script>

Upvotes: 0

johnny 5
johnny 5

Reputation: 21005

I don't know why they all aren't binding but aren't you look for the on change function? So you can just bind to that once?

//Untested
var Category = document.getElementsById('category');
Category.addEventListener("change", getQuestion, false);

Also, If you're not against Jquery, you might want to look into it it often gets rid of cross-browser issues. In Jquery:

 $('body').on('change', '#category', function() {
     getQuestion($(this));
 })

Upvotes: 1

Related Questions