Is it possible to assign a different value to the acquired value of an OPTION in a SELECT when submitting the form to PHP?


Well, I think the title of this question got confused, but I'll try to better detail my problem.

I'm developing a project with CodeIgniter framework (I'm a beginner) where I have a php/html page with a form that contains some data brought from the database into each <option> of a <select> :

<select id="estado" name="estado">
   <option selected disabled hidden>Selecione um estado</option>
      <?php foreach($estados as $uf): ?>

       <option value="<?php echo $uf->id_estado ?>">
            <?php echo $uf->estado ?></option>

    <?php endforeach; ?>


<select id="cidade" name="cidade">
   <option selected disabled hidden>Selecione uma cidade</option>

   <?php foreach($cidades as $cid): ?>

      <option value="<?php echo $cid->id_estado ?>">
         <?php echo $cid->cidade ?></option>

   <?php endforeach; ?>

In the <select> of the state the value is filled with the id of the state and the content with the name of the state.

In the city's <select> the value is filled with the foreign key referring to the state the city belongs to and the content with the city name.

The problem is that I need to pass the city id when submitting the form instead of the foreign key. I passed the key in place of the id precisely so that the cities to be displayed are only those belonging to the previously selected state.

This is the Javascript/Jquery code responsible for controlling the display:

$(document).ready(function() {
    $("#estado").change(function () {

 // a cidade inicia selecionado em "SELECIONE UMA CIDADE"
        $("#cidade").val($("#cidade option:first").val());

        var estado = document.getElementById("estado").value;
        var cidade = document.getElementById("cidade");

   for(var i = 0; i < cidade.length; i++){         
 /* se a chave estrangeira tiver o mesmo valor que o id do estado
  selecionado a opção será exibida, caso contrário a opção não aparecerá.*/

        if(cidade.options[i].value == estado){
            cidade.options[i].style.display = 'block';

            cidade.options[i].style.display = 'none';

I would like to know if it is possible to pass the city id to the form without affecting the display of these equivalent elements or if there is a more practical way to display this data and allow me to submit the correct id.

Thank you in advance who can help me!


I believe the best option is to store the state ids in the dataset attribute instead of the value .

echo "<option value='{$cid->id_cidade}' data-id_estado='{$cid->id_estado}'>{$cid->cidade}</option>"

That way you can retrieve the information with the dataset attribute using the declared key, in this case, id_estado

    if(cidade.options[i].dataset.id_estado == estado){
        cidade.options[i].style.display = 'block';
    } else{
        cidade.options[i].style.display = 'none';
Scroll to Top