Dynamically populate 3 dropdowns based on the selection in first dropdown - javascript

I have 4 dropdowns. Magazines, DD1, DD2, DD3. The dropdowns DD1, DD2, DD3 needs to be auto populated dynamically with the selection of a value in Magazine dropdown. The dropdowns DD1, DD2, DD3 are not dependent on each other. They purely depend on value in Magazines dropdown.
On the selection of dropdown 1 value, php ajax has to make call on mysql. I need to implement 3 different mysql queries in the background for 3 dropdowns.I surfed in net and all dropdowns are related to the previous dropdowns. For Example.
Can anybody guide me with proper link or proper idea to do this.

A quick workaround using javascript onchange:
form:
<select name="dd1" id="dd1" class="form-control" onChange="getDD2(this.value);">
<option value="" selected="selected">-select-</option>
</select>
javascript:
function getDD2(id){
if(id==""){
alert("Please select any dd1!");
}else{
var url = 'getdd2.php?id='+id;
$('#dd2container').load(url);
}
}
and in getdd2.php
$id = $_REQUEST['id'];
$dd= "SELECT * FROM prefix_dd2 WHERE id='$id'";
$founddd1 = $dbh->query($dd);
$res = $founddd1->fetchAll();
if(count($res)<=0){
echo '<select name="dd2" class="form-control" id="dd2">';
echo '<option value="select">No dd</option>';
echo "</select>";
}else{
echo '<select name="dd2" class="form-control" id="dd2" onchange="getDD3($id)">';
echo '<option value="select" selected="selected">-select-</option>';
foreach($res as $dd2):
echo '<option value="'.$dd2['id'].'">'.$dd2['dd2_name'].'</option>';
endforeach;
echo "</select>";
}
DD2 select in your form would be:
<div id="dd2container">
<select name="dd2" class="form-control">
<option value="" selected="selected">--select--</option>
</select>
</div>
Now you can make getDD3() function like I did getDD2() above. I hope this may help.
If you want to populate three select at one go, you can put all the three select box in the getdd2.php and query the database for each base on the data from the first select box.

Related

Populate dropdown2 from onChange event of dropdown1

I need to write a code where i need to populate a dropdown1 from mysql table based on the selection of another dropdown which also where in need to give values of dropdown as numeric value as item id from mysql table , but script.js not accepting any numeric value .Am quite new to this concept please help me to resolve this issue, thank you
HTML PART
<div>
<select class="custom-select" style="width: 150px;" id="dropdown1" onchange="onChange()">
<option selected disabled>Select Role </option>
<?php
enter code here
$sql = "SELECT * FROM category";
$result = $conn->query($sql);
//Populate dropdown2 from onChange event of dropdown1
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()){
echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
}
} else{
echo "Sorry No Role Availabe for Now";
}
$conn->close();
?>
</select><br/>
<span id="choosen"></span>
</div>
JS PART
<script>
function onChange(){
var idforquery =document.getElementById('dropdown').value;
document.getElementById("choosen").innerHTML="
// Here we generate another dropdown of behalf of selected dropdown option
<div>
<select class="custom-select" style="width: 150px;" id="dropdown1">
<option selected disabled>Select Role </option>
<?php
$sql2 = "SELECT * FROM sub_category WHERE cat_id =idforquery;";
$result = $conn->query($sql2);
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()){
echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
}
} else{
echo "Sorry No Role Availabe for Now";
}
$conn->close();
?>
</select><br/>
<span id="choosen1"></span>
</div>";
}
</script>
This is not going to work. PHP code is only executed when the client loads the page. If you want the <option> tags to change dynamicaly after the page has loaded, you need to use an asynchronous request (AJAX).
Here is a guide on how to use AJAX requests using PHP and jQuery.

Change content based on a drop down selection from a mysql database

I have a form of drop down boxes populated with values from a mysql database (Computer Part Models). My goal is to produce the rest of the values (The part's specs) from the database below each drop down box based on the value that was selected.
Essentially what I think I think I need is some sort of div refresh for each time a new item has been selected.
I have tried different functions triggered by 'onchange' within the select tag but nothing has come up working.
Let me know if anymore code would be needed for context.
HTML & PHP for one drop down
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<?php
$cresult = $mysqli->query("SELECT * FROM pCpu ORDER BY cModel asc");
?>
<select id="CPU" name="CPU">
<option value="" disabled selected>Select your Part</option>
<?php
while ($rows = $cresult->fetch_assoc()) {
$cmodel = $rows['cModel'];
echo "<option value='$cmodel'>$cmodel</option>";
$cid = $rows['ID'];
}
?>
</select>
<br/>
<?php
$res = $mysqli->query("SELECT cSocket FROM pCpu WHERE ID = '$cid'");
while($rows = $res->fetch_assoc()) {
$csocket = $rows['cSocket'];
echo "CPU Socket: $csocket<br/>";
}
?>
<br/><br/>
What would be the best way of tackling this?
Thanks in advance!
There's two parts in this answer :
First if you want to update a part of your page with change event on the select
function myUpdateFunc()
{
var mySelected = $("#CPU").find("option:selected").val();
$('#divResults').html ('selected value :' + mySelected)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<select id="CPU" name="CPU" onchange="myUpdateFunc()">
<option value="" disabled selected>Select your Part</option>
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
<br/>
<div id="divResults"/>
<br/><br/>
Next :
If you want to query a database you can check many tutorials on this. I can help you with this as well

Multiple Select Option in html while getting data from databse

I have to run a mysql query and make Select option to select the given data in my HTML form.
The issue is No of select option. Because I have to Select option on the basis of item quantity. For example I have one pizza and three drinks. then I need to open 1 select option for pizza and three select option for dirnks.
Here is my CODE:-
<select class="form-control" name="dealSizeName[]" id="dealSizeName">
<?php
$sql3 = mysql_query("SELECT * From `dealsubcategories` WHERE `Status` ='Y'");
while($row3 = mysql_fetch_array($sql3)) { ?>
<option value="<?=$row3['SizeName']." ".$row3['SubCategoryName']?>">
<?=$row3['SubCategoryName']?>
</option>
<?php } ?>
</select>
I have the following Table in my Database:
and I want to make select optoin in my html form like this:
If in DealA, qty of Pizza is 2 than open two select otion. For burger open 1, for Drink open 3 and for pasta open 1 select option box in my html form.
But I am getting one select option for all every time. How to make it dependable on qty filed of my table.
There is an attribute multiple for the select element which helps you choose multiple options.
Since I do not have any knowledge in PHP I will be adding html comments in what you should do in php. This is the basic gist that you should try.
<?php
$sql3 = mysql_query("SELECT * From `dealsubcategories` WHERE `Status` ='Y'");
<!-- for index = 0;index < subCategory.quantity; index ++ -->
<select class="form-control" name="dealSizeName[]" id="dealSizeName" multiple>
while($row3 = mysql_fetch_array($sql3)) { ?>
<option value="<?=$row3['SizeName']." ".$row3['SubCategoryName']?>"> <?=$row3['SubCategoryName']?></option>
</select>
<?php }?>

Filter HTML Dropdown Based on Another Dropdown Selection [duplicate]

This question already has answers here:
What's the best and easiest way to Populate a dropdown based on another dropdown
(2 answers)
Closed 6 years ago.
I have multiple HTML dropdowns. After one selection, I want it to automatically populate the next dropdown. All of this information is being brought in to populate the lists from a database using a SQL statement and foreach loop, so I cannot hard code the values like all of the examples out there related to my question. I currently have just a bit of JavaScript for this as of now although I am not sure if I am going in the right direction. I am thinking that this will need to involve some AJAX and an onChange listener. I am just unsure of how to get started.
So how can I do this? I am not asking for you to do this for me, but just some code (like an outline) to give me a head start and get me going would be appreciated! Thank you!
SQL Statements:
<?php
$host="xxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxxxxx";
$dbPass="xxxxxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM vProducts ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM vProducts ORDER BY [Minor Category] ASC";
$sql_code = "SELECT DISTINCT [Product Report Code] FROM vProducts ORDER BY [Product Report Code] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
$dropdown_code = $dbh->query($sql_code);
?>
Dropdowns:
<table cellspacing="5" align="center" id="dropdown-table">
<thead>
<tr>
<th>Major Category</th>
<th>Minor Category</th>
<th>Report Code</th>
<th>SKU</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select id="major" onChange="updateCat();">
<option value="" disabled="disabled" selected="selected">Please Select One</option>
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<option value="" disabled="disabled" selected="selected">Please Select One</option>
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select>
<option value="" disabled="disabled" selected="selected">Please Select One</option>
<?php foreach ($dropdown_code->fetchAll() as $drop_code): ?>
<option
value="code"
data-name="<?php echo $drop_code ['Product Report Code'];?>"
>
<?php echo $drop_code ['Product Report Code'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select>
<option value="" disabled="disabled" selected="selected">Please Select One</option>
<option value="sku">SKU</option>
</select>
</td>
<td><input type="button" value="Search" id="searchButton" onclick="show();"></td>
<td><button class="create-user" id="insertButton">Add Group</button></td>
</tr>
</tbody>
</table>
JavaScript:
// JS for Dropdown
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
As a starting point I would suggest looking at the W3schools section on AJAX PHP.
Using an AJAX PHP one approach to this would be to leverage the DOM onchange event of your dropdown to pass the selected value through to a PHP page via XMLHttpRequest in a javascript function.
The PHP page could then be set up to return the second list of values from the database. The returned data could be the elements for your second dropdown.
Looking at your code I would perform the first SQL query to generate the major category items in the main page where your table resides. The second SQL query for your minor category items would then reside in your second page where the AJAX call is made. The second query will only be invoked then when the value within your dropdowns are changed.
UPDATE 1: Adding some code
1. Major Items Select Box
Run your SQL query to generate your values for the major options.
<select id="majoritems" onChange="updateCat();">
<option value="" disabled="disabled" selected="selected">Please Select One</option>
<?php echo $major_options; ?>
2. Minor Items Select Box
<select id="minoritems">
<option value="" disabled="disabled" selected="selected">Please Select One</option>
3. Javascript AJAX Call
The following draws on the W3Schools AJAX PHP example primarily.
<script>function updateCat(val){
if (val.length == 0) {
document.getElementById("minoritems").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("minoritems").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getminoritems.php?q=" + val, true);
xmlhttp.send();
}}</script>
When the getminoritems.php page is called the URL parameters are set which will send the val variable across as a GET variable. This can then be used to query the items in the database based on that value.
4. Your PHP page to return the list of minor options based on the value sent in the AJAX GET call
In your PHP page you should now be able to access the $_GET variable q which was set in the AJAX call with the value of val. Taking this you can query your database, e.g.
$val = $_GET['q'];
$sql_minor = "SELECT DISTINCT [Minor Category] FROM vProducts WHERE category = $val ORDER BY [Minor Category] ASC";
etc etc...your code to return values
Make sure to return the values within <option>tags in the end. They will be output within in the minoritems select element as the javascript function uses the .innerhtml to set it to the response text received from your AJAX call.
Hope this helps!
PS: I would suggest doing a very very simple example using the W3schools tutorial if you can so that you can get your head fully around what is happening here.

retain drop down selection after form submission

I have an HTML form with multiple drop down menu fields that get populated looping thru arrays for select data common between multiple fields.
<label>Techician:</label>
<select name="rcvTech" id="rcvTech">
<option value="0">--Select Technician--</option>
<?php
foreach ($tech as $t) {
echo "<option value='$t'>$t</option>";
}
?>
</select>
What could I do to have the selected data for all drop down menus retained when the form is submitted so that if there are any errors to correct the user would not have the tedious task of having to re-select each field over?
Solution adapted from user5748817's post below:
<label>Receiving techician:</label>
<select name="rcvTech" id="rcvTech">
<option value="0" selected="selected">--Select Technician--</option>
<?php
foreach ($tech as $t) {
echo "<option value='$t'";
if (isset($_POST['submitted']) && $_POST['rcvTech'] == $t){
echo " selected";
}
echo ">$t</option>";
}
?>
</select>
To be able to handle the multiple selected options you would need to collect the data as an array. So change the select name to rcvTech[]. When validating the data submitted, collect it in a session to be able to get the submitted values.
<label>Techician:</label>
<select name="rcvTech[]" id="rcvTech">
<option value="0">--Select Technician--</option>
<?php
foreach ($tech as $t) {
if (in_array($t, $_SESSION['submitted'])) $selected=" selected";
echo "<option value='".$t."' ".$selected.">".$t."</option>";
}
?>
</select>

Categories