Retrieve label value from a select HTML

0

I have the following select:

<span class="IWLABEL11CSS" id="IWLABEL7">Órgão: </span>
<select name="Distrito" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1">
    <option value="01">Gabinete do Prefeito</option>
    <option value="02">Coordenadoria de Governo e Comunicação Social</option>
    <option value="03">Secertaria Municipal de Planejamento</option>
    <option value="04">Procuradoria Jurídica</option>
    <option value="05">Ouvidoria Municipal</option>
    <option value="06">Secretaria Municipal de Administração</option>
</select>

I would like to retrieve not only the value, but also the label, how could it be done?

    
asked by anonymous 27.12.2017 / 15:18

2 answers

2

In pure Javascript, just like the question tag, change the select to execute a function when the value is changed, through the onchange :

 <select name="Distrito" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1" onchange="mudouValor()">

Create the function mudouValor , responsible for getting the value of the label:

 function mudouValor() {
      //instancia um elemento do DOM através do respectivo id, que nesse caso é "COMBOFAB"
      var elemento = document.getElementById('COMBOFAB');
      //com o elemento instanciado, é possível capturar o valor da label
      var texto = elemento.options[elemento.selectedIndex].innerHTML;
 }

Directly with PHP will not be possible. You can, however, use Javascript to populate a field of type hidden on your form, for example:

 <form name="myform" id="myform" action="teste.php" method="POST">
     <span class="IWLABEL11CSS" id="IWLABEL7">Órgão: </span>
     <select name="Distrito" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1" onchange="mudouValor()">
         <option value="01">Gabinete do Prefeito</option>
         <option value="02">Coordenadoria de Governo e Comunicação Social</option>
         <option value="03">Secertaria Municipal de Planejamento</option>
         <option value="04">Procuradoria Jurídica</option>
         <option value="05">Ouvidoria Municipal</option>
         <option value="06">Secretaria Municipal de Administração</option>
     </select>
     <input type="hidden" name="label" id="label" />
</form>

Notice that the field of type hidden was added at the end of the form with value filled in with the value of the first option of select :

<input type="hidden" name="label" id="label" value="Gabinete do Prefeito" />

The problem of manually initializing the label field with the value corresponding to the first element of select is that if this value changes, the programmer also needs to change the value of the label field and certainly someone will forget that in the future, so we can automate this part:

window.onload = function(){
    mudouValor();
}

The Javascript code would look like this:

function mudouValor() {
      var elemento = document.getElementById('COMBOFAB');
      var texto = elemento.options[elemento.selectedIndex].innerHTML;

      //altera o valor do campo cujo o id seja igual a "label"
      document.getElementById("label").value = texto;
 }

 window.onload = function(){
    mudouValor();
 }

Note that for the example, the form has the action attribute set to the value teste.php and with the method attribute with the POST value, that is, a POST Request will be made to the file teste.php :

  <form name="myform" id="myform" action="teste.php" method="POST">

With this just create the file teste.php :

  <?php
      //Através da variável global "$_POST" é possível obter os valores do seu formulário.
      //Cada index do array "$_POST" representa um campo do formulário, ou seja, no formulário existe um campo com o atributo name="Distrito" e outro campo com o atributo name="label"
      $distrito = $_POST['Distrito'];
      $label= $_POST['label'];

      //...
  ?>

Change the names according to your need, the names above were defined for example only.

    
27.12.2017 / 15:36
1

Using Jquery (which I recommend you add to your project if you do not):

console.log($("#COMBOFAB option:selected" ).text()); //texto do item selecionado
console.log($("#COMBOFAB option:selected" ).val()); //valor do item selecionado
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanclass="IWLABEL11CSS" id="IWLABEL7">Órgão: </span>
<select name="Distrito" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1">
    <option value="01">Gabinete do Prefeito</option>
    <option value="02">Coordenadoria de Governo e Comunicação Social</option>
    <option value="03">Secertaria Municipal de Planejamento</option>
    <option value="04">Procuradoria Jurídica</option>
    <option value="05">Ouvidoria Municipal</option>
    <option value="06">Secretaria Municipal de Administração</option>
</select>

Using pure Javascript:

var e = document.getElementById("COMBOFAB");
var selectedValue = e.options[e.selectedIndex].value;
var selectedText = e.options[e.selectedIndex].text;

console.log(selectedValue); //valor do item selecionado

console.log(selectedText); //texto(label) do item selecionado
    <span class="IWLABEL11CSS" id="IWLABEL7">Órgão: </span>
    <select name="Distrito" size="1" width="180" class="COMBODISTCSS" id="COMBOFAB" tabindex="1">
        <option value="01">Gabinete do Prefeito</option>
        <option value="02">Coordenadoria de Governo e Comunicação Social</option>
        <option value="03">Secertaria Municipal de Planejamento</option>
        <option value="04">Procuradoria Jurídica</option>
        <option value="05">Ouvidoria Municipal</option>
        <option value="06">Secretaria Municipal de Administração</option>
    </select>

EDIT: I recommend you use Jquery, in addition to being cleaner, you will have a lot more facilities in the palm of your hand, to add Jquery via CDN you can paste this code in the Layout of your project, or in the pages which you will use:

<script
    src="https://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous">
</script>
    
27.12.2017 / 15:25