Why are you using blocks of script
and document.write
to write the options
? What comparison are you trying to make in the MudarOponente
?
I put in a code below what I understood you want.
I’m adding the event of onchange
by javascript because if the script is loaded after the <select>
the onchange
will not find the function.
The value entered in <select>
is the value of the attribute value
of <option>
selected, note that when I catch the this.value
is alerted to the added value in the attribute value
.
The this
within the function refers to the <select>
that invoked the action, so this.value
to take his worth.
var selectOponente = document.getElementById('selectOponente');
selectOponente.addEventListener('change', function() {
alert(this.value);
});
var formOponente = document.getElementById('formOponente');
formOponente.addEventListener('submit', function() {
if(!this.nome.value) {
alert('informe o nome pelo menos');
return;
}
if(!this.valor.value) {
this.valor.value = this.nome.value;
}
var opcao = document.createElement('option');
opcao.value = this.valor.value;
var textoOpcao = document.createTextNode(this.nome.value);
opcao.appendChild(textoOpcao);
selectOponente.appendChild(opcao);
this.nome.value = null;
this.valor.value = null;
});
<select id="selectOponente"></select>
<hr />
<form id="formOponente">
<label>Nome</label> <br />
<input name="nome" type="text"/>
<br />
<label>Valor</label> <br />
<input name="valor" type="text" />
<br />
<input type="submit" value="Cadastrar" />
</form>
UPDATE
See that I put in it snippet
update with a form to insert the values in a <select>
. With pure javascript is something very "massante". I suggest that I study some javascript framework to help you do this in an easier way like jQuery
, AngularJS
, VueJS
, AureliaJS
, EmberJS
and so on, there are many haha
Can you give an example of how it should look? This "text" that corresponds to each option comes from where? It is already in HTML or comes from the server?
– Sergio