First Drop Down Menu to Auto Change the Options of a Second Dropdown

Auto change second dropdown when selecting the first option

Use data-* attribute to differentiate among fruit and vegetable





var category = document.getElementById('category');

document.getElementById('elements').onchange = function() {

var optionSelected = this.options[this.selectedIndex];

if (optionSelected.textContent != '-') {

if (optionSelected.dataset.val === 'veg') {

category.value = 'veg';

} else {

category.value = 'fruit';

}

} else {

category.value = '';

}

}
<select name="" id="elements">

<option value="">-</option>

<option value="">Apple</option>

<option value="">Orange</option>

<option data-val='veg' value="">Cucumber</option>

<!-- veg -->

<option value="">Banana</option>

<option value="">Grapes</option>

<option data-val='veg' value="">Onion</option>

<!-- veg -->

<option data-val='veg' value="">Tomato</option>

<!-- veg -->

</select>


<select name="" id="category">

<option value="">-</option>

<option value="fruit">Fruit</option>

<option value="veg">Vegetable</option>

</select>

First drop down menu to auto change the options of a second dropdown

See below to see the Working Example without using a Database.

Working Example Using MySQL Database

If you wanna connect it using Database, yeah, it is surely possible. Consider this table:

CREATE TABLE `contents` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR (255),
`parent` INT DEFAULT 0
);

INSERT INTO `contents` (`name`, `parent`) VALUES
('Names', 0),
('Places', 0),
('Animals', 0),
('Praveen', 1),
('Bill Gates', 1),
('Steve Jobs', 1),
('India', 2),
('New York', 2),
('London', 2),
('Singapore', 2),
('Cat', 3),
('Dog', 3),
('Tiger', 3),
('Deer', 3)

Table Structure

+----+------------+--------+
| id | name | parent |
+----+------------+--------+
| 1 | Names | 0 |
| 2 | Places | 0 |
| 3 | Animals | 0 |
| 4 | Praveen | 1 |
| 5 | Bill Gates | 1 |
| 6 | Steve Jobs | 1 |
| 7 | India | 2 |
| 8 | New York | 2 |
| 9 | London | 2 |
| 10 | Singapore | 2 |
| 11 | Cat | 3 |
| 12 | Dog | 3 |
| 13 | Tiger | 3 |
| 14 | Deer | 3 |
+----+------------+--------+

Initial HTML & PHP Code

Now, lets use PHP to first populate the initial <select>:

<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = 0");
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>

Now the <select> is ready. With its onchange function, we can fire an AJAX event to get the new <select> with the data provided by the parent <select>.

<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>

Now for the jQuery function, you can do this way:

<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>

In the HTML, after the <select>, you need to give another select with an id as sub.

<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
<select id="sub"></select>

Processing PHP Source Code

Finally the source code of process.php:

<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = " . mysql_real_escape_string($_GET["parent"]));
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>

Working Example without using a Database

You just need to replace this in the PHP.

<?php
$parent = array("Name", "Place", "Animals");
foreach ($parent as $id => $name)
echo '<option value="s', $id,'">', $name,'</option>'
?>

And for the process.php:

<?php
$parent = array("Name", "Place", "Animals");
$s0 = array("Praveen", "Bill Gates", "Steve Jobs");
foreach (${$_GET["parent"]} as $id => $name)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>

First Dropdown Changes Second Dropdown Related Item display

Here is a working demo you could follow:

<div class="input-group input-group-sm">
<select id="OrderType" title="Mode" class="form-control form-control-sm border selectpicker" >
<option id="DomId" value="1">Domestic</option>
<option id="InterId" value="2">International</option>
</select>
</div>
<div class="input-group input-group-sm">
<select id="CurrencyType" title="Mode" class="form-control form-control-sm border selectpicker">
<option value="" selected>Select A Currency</option>
</select>
</div>

@section Scripts
{
<script>
$(function () {
var subjectObject = {
"1": [
"INR"
],
"2": [
"USD",
"EUR"
]
};
$('#OrderType').change(function () {
var OrderType = $(this).val()
var CurrencyType = subjectObject[OrderType] || [];

var html = $.map(CurrencyType, function (cnt) {
return '<option value="' + OrderType + '">' + cnt + '</option>'
}).join('');
$('#CurrencyType').html(html)
});
})
</script>
}

A JSFiddle you could check: https://jsfiddle.net/b6pe3vxq/

Second drop down menu changing its value automatically

You should call the function when page is loaded

<script>
$(document).ready(function() {
ajaxfunction();
});

function ajaxfunction(parent){
$('.control').change(function(){
var Value = $(this).val();
if(Value != null){
jQuery.ajax({
type: 'POST',
url: "name.php?comp_type="+Value,
success: function(data){
$('#name').html(data);
}
});
}
})

}
</script>

Populating second drop down menu based on first drop down menu selection

Yes, JavaScript can be used to achieve the above-said functionality. The flow will be, first user will select a value from the first dropdown and you have to listen to onchange event on the first dropdown and make the API call in its onchange callback function. And then add the options based on the response received from API call. For adding options you have to manipulate the dom using js.

I tried to create a similar example with 3 dropdowns using static data instead of API (in your case) some time ago. I used jQuery in it. Please refer to this github link to get the idea about dom manipulation.

Change second drop down list depending on first drop down list and third drop down on second dropdown selection using php and arrays

You can do what you asked by selecting the options by their value:
The filter function you were using was removing all the option apart from the one that was selected.

find('option[value="' + i + '"]');

http://jsfiddle.net/nQBK2/4/

select1 = $('#select1');
select2 = $('#select2');
select3 = $('#select3');

$(select1).change(function() {
var i = $(this).val();
$(select2).find('option[value="' + i + '"]').prop('selected', true);
});

$(select2).change(function() {
var i = $(this).val();
$(select3).find('option[value="' + i + '"]').prop('selected', true);
});

Populating Second Dropdown Based on first dropdown from the database table without using javascript

You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you

https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php

OR

https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/

How to auto select second dropdown option/category populated by mysql pdo fetch, based on first html dropdown select

if you can change the values of the first select and the ids of your round divs this would be easier. But if you can't you can use a switch statement and assign the numeric value to your catlist select list.

<script>

$(function() {




$('.questionselector').change(function(){
var roundNumber;


switch($(this).val())
{
case "one":
roundNumber = 1;
break;
case "two":
roundNumber = 2;
break;
case "three":
roundNumber = 3;
break;
case "four":
roundNumber = 4;
break;
case "five":
roundNumber = 5;
break;
case "six":
roundNumber = 6;
break;
}


$('.rounds').hide();
$('#' + $(this).val()).show();
$('#catlist').val(roundNumber);
});
});
</script>

HTML Form first dropdown auto change the second dropdown options

Working example: http://jsfiddle.net/7YeL6/4/

Given this structure:

     <select name="category" id="category">
<option selected value="Please Select">Please Select</option>
<option value="Cars">Cars</option>
<option value="Trucks">Trucks</option>
<option value="Motorcycles">Motorcycles</option>
<option value="Boats">Boats</option>
</select>

<div>
<select name="category2" id="truck" class="second">
<option value="white">white</option>
<option value="black">black</option>
</select>

<select name="category2" id="car" class="second">
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
</div>

You could use jQuery .change function:

       $("#category").change(function () {
var str = "";
str = $("select#category option:selected").text();
if(str == "Trucks"){
$("select.second").not("#truck").hide();
$("#truck").show();
$("#truck").fadeIn(1000);
}
else if(str == "Cars"){
$("select.second").not("#car").hide();
$("#car").show();
$("#car").fadeIn(1000);
}

})

CSS

#category2{
display: none;
}


Related Topics



Leave a reply



Submit