Retrieve label value from select HTML

Asked

Viewed 893 times

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 recover not only the value, but the label as well, as could be done?

  • 1

    Why did you use the tag PHP on the question? Do you want to know how this is done with PHP (although I’m not only good with PHP) or Javascriot?

  • in any of these I could use, because it is a web system that uses these technologies

2 answers

2


In pure Javascript, such as the question tag, change the select to execute a function when the value is changed, via the event onchange:

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

Create the function mudouValor, responsible for obtaining 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. However, you can use Javascript to fill in a field of type hidden in 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>

Note that the type field was added at the end of the form hidden with the value filled 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 field label with the value corresponding to the first element of select is that if this value changes, the programmer also needs to change the value country label and surely someone will forget that in the future, so we can automate that 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 is with the attribute action defined with the value teste.php and with the attribute method with the value POST, that is, a POST Request will be made for 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 as needed, the names above have been defined for example only.

  • so I recover only the selected or all?

  • Only the selected, see the variable texto within the function mudouValor, it is populated according to the selected element and this is possible using the elemento.selectedIndex along with elemento.options.

  • this select was already inside a form, it was this: <form method="post" action="""> it is necessary to put name and id?

  • It is not necessary to put a name or id in the form. You have to create the hidden I have quoted above within the form and amend the select adding the event onchange, as explained above.

  • I made these modifications, but it didn’t work, I’m seeing if there’s something wrong here

  • Check the browser console for any javascript errors. Javascript works, see here an example.

  • would have some problem having other inputs in the form?

  • @V.Avancini not, as long as they do not have the same ID. Changing the field ID hidden that we created, then we need to change the function mudouValor to consider the new ID.

  • for some reason the $_POST is not sending the information

Show 5 more comments

1

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

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>
<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>

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, besides being cleaner, you will have a lot of 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 you will use:

<script
    src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous">
</script>
  • how would you store in a php variable?

  • $var = $("#COMBOFAB option:Selected" ).text()); ??

  • @V.Avancini I’ll find out, I haven’t used PHP in a while

  • if you manage and send here mark as accepted

  • I’ll find out, but in case someone finds it, I’ll check it as correct ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.