Reputation: 65
I am following this tutorial - http://www.thesoftwareguy.in/multiple-dropdown-with-jquery-ajax-and-php/
If you have a look at the demo - http://demos.thesoftwareguy.in/multiple-dropdown-jquery-ajax-php/ the second select appears once the first choice is made. While the third box appears when the second choice is made.
This is the ajax code:
function showState(sel) {
var primary_cat = sel.options[sel.selectedIndex].value;
$("#output1").html("");
$("#output2").html("");
if (primary_cat.length > 0) {
$.ajax({
type: "POST",
url: "fetch_state.php",
data: "primary_cat=" + primary_cat,
cache: false,
beforeSend: function() {
$('#output1').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#output1").html(html);
}
});
How can I made the second dropdown menu always appear, rather than appear and dissapear upon choice? I would still the same like it to populate whenever the first choice is made.
I tried eliminating lines
beforeSend: function() {
$('#output1').html('<img src="loader.gif" alt="" width="24" height="24">');
},
and
success: function(html) {
$("#output1").html(html);
}
Individually and together but then it does not work.
Excuse my boring question but I'm still learning PHP and AJAX
Upvotes: 1
Views: 591
Reputation: 3709
If you want to show both select
tags, you will need to create a default value on the first select, since there have to be options for the second one based on the first one.
So what I would do is:
<option value="">Please Select</option>
in the landing page from the <select name="country" ...>
Add the following code to the <script>
where the showState
function is defined (but before and outside the function):
$(function(){
$('select[name=country]').trigger('onchange');
});
Like this you have a default value on the first select and the second one will always show with the options matching the selection in the first select.
Upvotes: 1