Skip to content

How to pass an array from HTML to Javascript?

I have a form which has multiple <select> drop-down boxes. I wish to pass the value in these drop-down boxes as an array to a JavaScript function.

Currently my code is like:

<select name="findByMaterial" onChange="filterFilms('Material',this.value)">
                    {% for film in all_films %}
                        <option value="{{film.f_material}}">{{film.f_material}}</option>
                    {% endfor %}

Where all_films is a variable from Django framework (Most probably you need not concern yourself with it).

What I want to do is that even if I have multiple selects with different names such as findByMaterial and findByColor, and I change the findByColor, then it should call the filterFilms(String,Value) JS function.

Any pointers in the right direction would be appreciated a lot.

PS: This question is probably similar to how to pass array values to JavaScript function from html onchange action?, but it is definitely not what I am looking for.

CLarification: I wish to create a filter. Thus I would want to be able to access the attribute of color as well as material.


Online Demo :

<html lang = "en">
        <title> Document </title>
            function filterFilms(selectBox) {
                var displayArea = document.getElementById("displayArea");
                displayArea.innerHTML = + "," + selectBox.value + "," + selectBox.selectedIndex + "," +
        <select onchange="filterFilms(this);" id="films">
            <option value="film1">Film Text 1</option>
            <option value="film2">Film Text 2</option>
            <option value="film3">Film Text 3</option>

        <select onchange="filterFilms(this);" id="colors">
            <option value="color1">Color 1</option>
            <option value="color2">Color 2</option>
            <option value="color3">Color 3</option>

        <div id="displayArea"/>

You can use the same function to do this. Pass the current element as the parameter. And

  1. You can get the id of the select box clicked with
  2. You can get the selected option’s value with selectBox.value
  3. You can get the selected option’s index with selectBox.selectedIndex
  4. You can get the selected option’s text with selectBox.options[selectBox.selectedIndex].text