Show name according to select in other input

0

I have a table where I have, the id, department code and the full name of this and what I want is that when I select an option, the full name of the department appears but it is only showing me the id

I have this function to do that

 function cambioOpciones()
    {

   document.getElementById('dep').value=document.getElementById('cod').value;

    }

and the select code so

   <select class="form-control" name="cod" id="cod" onchange="cambioOpciones();">
               <option>Seleccione el departamento</option>
              <?php foreach ($dep as $d):?>
               <option value="<?php echo $d['id'];?>"><?php echo ucwords($d['cod_dep']);?></option>
            <?php endforeach;?>
          </select>
    
asked by Mar 14.07.2018 в 04:41
source

1 answer

1

If the department name is in the text of the select options you present, you can do this.

I have put test data, since I do not have access to your server code.

I have made some changes. For example, as good practice 1 it is recommended to avoid having calls to functions within the HTML elements. That's why you'll see that I've removed onChange from select . You can listen to the changes from the Javascript code using the id of the element. In addition, this gives you the advantage of using this , through which you can access any value or property of the element.

Here I have assumed that you want to show the data in input , and its value is updated according to the selected department, taking its value and the text that is written in it.

var cboCodigos = document.getElementById('cod');
var ibxDepartamento = document.getElementById('dep');

cboCodigos.onchange = function() {
  var cboText = this.options[this.selectedIndex].innerHTML;
  var cboValue = this.value;
  ibxDepartamento.value = cboValue + ": " + cboText;
};
<select class="form-control" name="cod" id="cod">
  <option>Seleccione el departamento</option>
  <option value="1">Departamento 1</option>
  <option value="2">Departamento 2</option>
  <option value="3">Departamento 3</option>
</select>
<hr />
<input id="dep" type="text" />

Notes:

1 This practice is recommended to have the code as independent as possible. If you have hundreds of HTML elements that use the same function and you have to change something like the name of the function, you will have to look for the hundreds or thousands of files where that function is invoked to change it. Instead, listening for the id you can change what you want in the Javascript code without affecting your HTML files.

    
answered by 14.07.2018 в 05:15