Find the answer to your question below.
var opcao = document.getElementById('teste'); //busca o select
function extrair(separador){ //funcao extrair que retorna um array com os valores
if(opcao.selectedIndex!=0) return opcao.value.split(separador); //separa os valores pelo [separador]
}
opcao.onchange=function(){ //evento de mudanca de estado
var valores = extrair('|'); //inicializa a funca extrair para obter os resultados
console.log(valores); //lista o array
console.log("Valor 1: "+valores[0]); //lista valor 1
console.log("Valor 2: "+valores[1]); //list valor 2
}
<!DOCTYPE html>
<html>
<head>
<title>Como fazer múltiplos valores em um único option e recupera-los</title>
</head>
<body>
<select id="teste">
<option>Selecione uma opcao</option>
<option value="valor1|valor2" >Opcao 1</option>
</select>
</body>
</html>
If you do not want to use the property onchange
element can always add an eventListener opcao.addEventListener(EVENTO, FUNCAO)
.
opcao.addEventListener('change', function(){
var valores = extrair('|'); //inicializa a funca extrair para obter os resultados
console.log(valores); //lista o array
console.log("Valor 1 no event listener: "+valores[0]); //lista valor 1
console.log("Valor 2 no event listener: "+valores[1]); //list valor 2
})
Try to explain the code you use, and why you do so. (note: the
onchange
assigned this way will do rewrite to the property)– MoshMage
@Moshmage as such (in relation to rewrite) ? Could you explain to me what that would be and how, in this case, to write the right code ?
– Paulo Gustavo
@Moshmage used the onchange just to set the example. More by defining the event onchange has no action.
– Gonsalo Sousa
@Gonsalosousa the downvote is not for the use of on-change, it is because this although it answers the question - does not explain to the user the why to solve the question nor what this one was doing wrong
– MoshMage
@Moshmage and where Oce explained to the user what he was doing wrong? Read again the question, the onchange was just an extra. The questioner demonstrates basic knowledge, and just asks how to recover the values. Your downvote was misplaced...
– Gonsalo Sousa
@Gonsalosousa It’s not about with this user but yes with the next, although yes my dv has been hasty (but that’s why these take time to be saved).
– MoshMage
@Gonsalosousa This cool, served me as inspiration now I will leave my vote. Att+
– Diego Henrique