eduardoimm
eduardoimm

Reputation: 11

How can I make a decision according to the value of selectedIndex

I want to make an audio HTML tag to change its source according to the option that is selected in a select tag, how can I do that?

I'm thinking about something like this in the index.html file:

<script src="hola.js"></script>
<form name="datos">
    <select id="idioma">
        <option value="es">Español</option>
        <option value="en">Inglés</option>
    </select>
    <br />
    <button id="boton">Cambiar idioma</button>

</form>
<audio controls="controls" id="audio">Audio no disponible, para mejor funcionamiento, utilize Mozilla Firefox</audio>   

and this in the hola.js file:

var button=document.getElementById("boton");
var idioma=document.getElementById("idioma");
var audio=document.getElementById("audio");
var lang=document.datos.idioma.options[idioma.selectedIndex].value;

button.addEventListener("click",function(){

if(lang="es"){
    audio.setAttribute("src", "audio/es.ogg");
}else if(lang="en"){
    audio.setAttribute("src", "audio/en.ogg");
}
});

Upvotes: 1

Views: 78

Answers (1)

bagonyi
bagonyi

Reputation: 3328

Move lang variable declaration within the event listener:

var button = document.getElementById("boton"),
    idioma = document.getElementById("idioma"),
    audio = document.getElementById("audio");

document.getElementsByTagName('body')[0].appendChild(audio);

button.addEventListener("click", function () {
    var lang = document.datos.idioma.options[idioma.selectedIndex].value;

    if (lang = "es") {
        audio.setAttribute("src", "audio/es.ogg");
        audio.play();
    } else if (lang = "en") {
        audio.setAttribute("src", "audio/en.ogg");
        audio.play();
    }
});

Upvotes: 0

Related Questions