You can do it with JQuery
, I'll give you a simple example that I do with Estados
and Condados
where you select a state and in a Select
different you display the counties corresponding to that state.
Description of the code: I have a form which in the Select
of the states I previously sent the data to show all the states in that Select
by means of PHP
, in JQuery
I say that if the SelectState
changes then empty the SelectCounty
and that same add the data that brings the query of getJSON
, for this the URL
that I am adding in the getJSON
and returns me the data of Condados
by means of the Value
that has the SelectState
.
Code HTML
and PHP
:
<form id="form" action="<?echo base_url('index/savePost')?>" method="post">
<p class="spaceleft">State:</p>
<div class="centered">
<select id="selectState" class="select" name="form[state]" required>
<option value="" disabled selected value>Select One</option>
<?php foreach($States as $State){?>
<option value="<?php echo $State['id']?>"><?php echo $State['name']?></option>
<?php } ?>
</select>
</div>
<p class="spaceleft">County:</p>
<div class="centered">
<select id="selectCounty" class="select" name="form[county]" disabled required>
<option value="" disabled selected value>Select One</option>
</select>
</div>
<div class="centeredlimit">
<button type="submit" class="auto-style2">Send</button>
</div>
</form>
Code JS
:
$(document).ready(function(){
var selectState = $('#selectState');
var selectCounty = $('#selectCounty');
selectState.change(function() {
selectCounty.empty();
selectCounty.append('<option value="" disabled selected value>Select One</option>');
$.getJSON('<?php echo base_url('Index/getCountiesJson?id=')?>'+selectState.val(),function(data){
$.each(data.Counties, function(index,value){
selectCounty.append('<option value="'+value.id+'">'+value.name+'</option>');
});
selectCounty.prop('disabled', false);
});
});
});
In this case I have only the SelectState
activated and the other SelectCounty
I have it in Disabled
that's why I use selectCounty.prop('disabled', false);
so that it is now active Select
.