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
Related
I have created a dynamic dropdown list and the first <select name="club" id="club"> dropdown list will show the results of the mysql query below.
The second <select name="player" id="player"> will be filled by the result of the query which is used in the ajax.php based on the id of the selection in the first
I will use this principal to select a player from a club.
For the selection of one club and player this is working fine, but how can I extend this small piece of code to use this for selecting for example 10 players.
So in this case I have created 10 select boxes among each other which I would prefer to use this small piece of code instead of copying this code 10 times.
$strQueryClubs = "SELECT ec.id, ec.name
FROM club ec, season ss
WHERE ec.season_id = ss.id
AND ss.status = 1 /* Active season*/
ORDER BY ec.name asc";
$resultQueryClubs = mysql_query ($strQueryClubs);
$numQueryClubs = mysql_numrows ($resultQueryClubs);
$arrQueryClubs = $objDB->fetch_array($strQueryClubs);
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#club').on('change',function(){
var clubID = $(this).val();
if(clubID){
$.ajax({
type:'POST',
url:'ajax.php',
data:'id='+clubID,
success:function(html){
$('#player').html(html);
}
});
}else{
$('#player').html('<option value="">First select a club</option>');
}
});
});
</script>
<!-- language: lang-html -->
<select name="club" id="club">
<option value="" disabled="disabled">Select club</option>
<?php
if ($numQueryClubs > 0)
{
for ($i=0;$i<$numQueryClubs;$i++)
{
echo "<option value=".$arrQueryClubs[$i]['id'].">".$arrQueryClubs[$i]['name']."</option>";
}
}
else
{
echo '<option value="">Club is not available</option>';
}
?>
</select>
<select name="player" id="player">
<option value="" disabled="disabled">Select player</option>
</select>
<select name="club" id="club">
<option value="" disabled="disabled">Select club</option>
<?php
if ($numQueryClubs > 0)
{
for ($i=0;$i<$numQueryClubs;$i++)
{
echo "<option value=".$arrQueryClubs[$i]['id'].">".$arrQueryClubs[$i]['name']."</option>";
}
}
else
{
echo '<option value="">Club is not available</option>';
}
?>
</select>
<select name="player" id="player">
<option value="" disabled="disabled">Select player</option>
</select>
As Rasclatt mention in comment,listen event for class not id
As your requeriment of selecting 11 players, don't use 11 dropdowns.
I will suggest use multiple select by multiple property in select or any other plugins to avoid select perticular player twice.
Otherwise you need to refresh follwing dropdown to remove previously selected player
I have a set of drop down menus (HTML selects) which are populated with the same values from a mysql query. I would like that, as soon as I choose one option from a drop down, that option can't be selected in none of the rest (or appear disabled). Basically, this is what I have:
<form name="test" method="post" action="confirmSelection.php">
<select name="color1" id="color1">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
<select name="color2" id="color2">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
<select name="color3" id="color3">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
Any idea? I guess it must be simple but I don't really know how to look for it (it was really hard for me to find a proper title for this consult...).
Thanks a lot in advance.
EDIT:
ajax code:
function showData(dataType)
{
var capa=document.getElementById("content");
var ajax=nuevoAjax();
capa.innerHTML="";
ajax.open("POST", "test.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("d="+dataType);
ajax.onreadystatechange=function()
{
if (ajax.readyState==4)
{
capa.innerHTML=ajax.responseText;
}
}
}
In test.php is where I have the 4, 5 and 6 selectors in the same way I explained the 3. I also have this:
....
$dataType=$_POST['d'];
if($dataType=='1')
{
//4 selectors
}elseif($dataType == '2')
{
//5 selectors
}elseif($dataType == '3')
{
//6 selectors
}
The div is updating properly and showing the correct layout (4,5 or 6 selects) but the code you gave me is not working. I´ve tried including the javascript in test.php and in landscape.php. No luck :(.
Leave the PHP aside for this. You'll have a pure HTML page, once the PHP has done its thing, right? So the javascript simply has to interact with the DOM itself, as normal.
First, I wanted to store selected options for all the select elements, in an array. Doing this allows me to select an option in the first and the second color selectors, and have them BOTH disabled in the third.
Then, simply iterate over all the connected selects (I've connected them via a matching class), and within that iterate over all the selected options, and disable them as appropriate.
Sounds simple, but it was a bit of a challenge. More of a challenge (but not much more) might be to allow multi-selects.
Hope it helps, let me know if it needs a change.
// This array will be used to store the current selection of
// each connected select. They are connected by a class attr.
var selectedOption = new Array($(".colorSelector").length);
/*******
* Any time any select is changed, we update the selectedOption
* array to include the new selection. Note that the array is
* the same length as the number of selects, and that we're
* setting the value to the position in that array that relates
* to the position of the element itself. By this, I mean that
* selectedOption[0] contains the value of select[0],
* selectedOption[4] contains the value of select[4],
* and so on.
*******/
$("body").on("change",".colorSelector", function() {
// First, get the value of the selected option.
selectedOption[$(this).index()] = $(this).val();
/***
* Now, we iterate over every connected select element.
* we want to disable all values that are selected in
* all other connected selects -- those values we've stored
* in the selectedOption array. As long as the value is
* not blank, or the default '...', or the current element,
* we disable that option.
***/
$(".colorSelector").each(function() {
// First, re-enable all options.
$(this).children("option").removeAttr("disabled");
// Iterate over the selectedOption list
for (i = 0; i < selectedOption.length; i++) {
if (selectedOption[i] != "" && selectedOption[i] != "..." && i != $(this).index()) {
// Disable any option that isn't default, or
// ignore if the current selectedOption points to
// this select.
$(this).children("option[value='" + selectedOption[i] + "']").attr("disabled", "disabled");
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="color1" id="color1" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
<select name="color2" id="color0" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
<select name="color3" id="color3" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
Also, this is up as a fiddle, just in case.
EDIT: You mention that this doesn't work when the select is populated by AJAX. You're exactly right, it didn't work as written. The reason is, when an element is loaded after the page has loaded, it doesn't automatically connect to the page's current listeners. Instead, I've changed where the listener is attached in the above code. Instead of listening like $(".colorSelector").on("change"...), I've changed it to $("body").on("change", ".colorSelector", function(){...}); -- note that the listener now gets attached to the body. Doing this causes any element with the .colorSelector class to trigger, whether it was there initially or added later. Hope this helps!
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.
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.
I'm currently a beginner in javascript and i'm having a hard time passing the value of a dropdown box. I only know how to get the value into php if I wrap the select stuff into a post form and create a button to get the values when it's clicked but since this is javascript there isn't a submit button and I need to update the second dropdown list based on the value of the first dropdown list and update the third dropdown list based on the first and second values.
My table looks like this:
Currently, what my code does is it only stores the values inside the dropdown boxes. What I wanted it to do is if "guy" chooses January and chooses week 1, year should only contain 2015 and when he chooses week 2, year should only contain 2013.
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("my_db") or die (mysql_error());
$queryMonth = mysql_query("SELECT DISTINCT month FROM list WHERE username='guy'");
$queryWeek = mysql_query("SELECT DISTINCT week FROM list WHERE username='guy', month='Should be the value of the first select'");
$queryYear = mysql_query("SELECT DISTINCT year FROM list WHERE username='guy', month='Should be the value of the first select', week='Should be the value of the second select'");
?>
<html>
<head>
<script src="js/javascript.js"></script>
<script>
function getMonth() {
document.getElementById("monthchoice").value = document.getElementById("month").value;
}
function getWeek() {
document.getElementById("weekchoice").value = document.getElementById("week").value;
}
function getYear() {
document.getElementById("yearchoice").value = document.getElementById("year").value;
}
</script>
</head>
<body>
<select id="month" onchange="getMonth()" >
<option value="" disabled selected>Select your option</option>
<?php
while($getMonth = mysql_fetch_assoc($queryMonth))
{
echo
'
<option value="'.$getMonth['month'].'">'.$getMonth['month'].'</option>
';
}
?>
</select>
<select id="week" onchange="getWeek()" >
<option value="" disabled selected>Select your option</option>
<?php
while($getWeek = mysql_fetch_assoc($queryWeek))
{
echo
'
<option value="'.$getWeek['week'].'">'.$getWeek['week'].'</option>
';
}
?>
</select>
<select id="year" onchange="getYear()" >
<option value="" disabled selected>Select your option</option>
<?php
while($getYear = mysql_fetch_assoc($queryYear))
{
echo
'
<option value="'.$getYear['year'].'">'.$getYear['year'].'</option>
';
}
?>
</select>
<br><br>
<input type="text" id="monthchoice"><br>
<input type="text" id="weekchoice"><br>
<input type="text" id="yearchoice"><br>
</body>
</html>
You should research for ajax.
http://www.w3schools.com/ajax/ajax_intro.asp
When your dropdownboxvalue's value is changed. You can use ajax to request new data from the server. The server should return json datatype or xml if you want. Then you parse the data you receive from server into javascript object. Then use javascript to replace the old dropdownboxvalue value into new dropdownboxvalue you receive from the server before (i recommend u use jquery because it is quiet easy to use for beginner)