Well, I think the title of this question has been confusing, but I'll try to get a better understanding of my problem.
I'm developing a project with the 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 every <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>
<br><br>
<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; ?>
</select>
In%% of state, value is populated with state id and content with state name.
In%% of the city the value is filled with the foreign key referring to the state in which the city belongs and the content with the name of the city.
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 just so that the cities to be displayed are only those belonging to the state selected above.
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';
}
else{
cidade.options[i].style.display = 'none';
}
}
}).change();
});
I would like to know if it is possible to pass the id of the city 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 send the correct id.
Thank you in advance for your help!