Working with Select options coming from database - javascript

I have two select on my form the first get all its elements from a table named "department" in my school database.
It is working no problem, but my question is how to make the second select option box receive elements coming from the table "class" having column "departmentid" which is equal to the selected department in the first select option I mean if the user selects department "IT" the second select option may bring classes"4,5,6" because they were registered with the ID of that department.
The reason i am doing this is because all the departments don't have the same classes, It would be great if this event occured after clicking on the first select option.
My Database name is "School"
Table1 "departments" with its columns "Departmentid,Name"
Table2 "Class" with its columns "classid,level,Departmentid"
//First Select Option
<select class="form-control">
<option selected="selected">Show All Departments</option>
<?php
$link = mysqli_connect("localhost", "root", "", "school");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());}
$con="SELECT * FROM departments";
$query_test = mysqli_query($link,$con) or die ("MySQL error: " .mysqli_error($link) ." Query: $query");
while($row=mysqli_fetch_array($query_test))
{
$result=$row['Name'];
$results=$row['Departmentid'];
?>
<option name="find"value="<?php echo $row['Name'];?>"><?php echo $row['Name'];?></option>
<?php
}
?>
</select>
//Second select option
<select class="form-control">
<option selected="selected">Show All Classes</option>
//Input those classes in this select option
<option> </Option>
</select>

AJAX is the way to go.
On departement change call AJAX function with departement ID as data.
Make a query to get all classes of departement and return result.
Update classes options with those you get using Javascript.

Related

How do I pass multiple values through <option> value?

I'm making a online shopping item page,
it gets the 'item_id' to loop through a item info db to show its info on the page(price,image,name,whatev)
while using that same 'item_id' to loop through an inventory table(the inventory table has color_id, size_id ,item_id and storage_id) to render a drop down menu(select) to show its color options of that specific item,
i'm using ajax to get the size options of that color_id from the same inventory table. but i can't get the both 'item_id' and color_id passed through the color to narrow down the query together with color_id .
is there a way that i can pass both color_id and item_id through the rendered color to query in inventory table to get the storage_id? because right now i can't narrow it down the the specific item, it gets the size option of a specific color(color_id) but of all items, if without item_id
basically i'm trying to filtering down to the specific storage_id using two drop down menu(color_id ,size_id and product_id) of same table. but having trouble passing 2 (or multiple) values at once.
hope this makes sense?
<select class="form-control" id="colorSelector" onchange = "getSize(this.value)">
<option value="">Select Color</option>
<?php show_color_option()?> --->this is another function to render the colors using item_id
</select>
function getSize(val){
$.ajax({
type:'POST',
url:'sizeoptions.php',
data:"color_id="+ val,
success:function(data){
$('#sizeSelect').html(data);
}
});
}
function getSku(val){
}
///////////////////////////////////sizeoptions.php//////////////////
<?php
if(isset($_POST['color_id'])){
$query = query("SELECT size_id FROM inventory WHERE color_id =
".escape_string($_POST['color_id'])." GROUP BY size_id ");
confirm($query);
while($row = fetch_array($query)){
$p_size = display_size($row['size_id']);
$size_options = <<<DELIMETER
<option value="{$row['size_id']}"> {$p_size} </option>
DELIMETER;
echo $size_options;
}
}
?>
You can get extra information from select box using attributes.
<select class="form-control" id="colorSelector" onchange = "getSize()">
<option value="xyz" extra-attr="abc">Select Color</option>
</select>
function getSize(){
var selectedXYZ = $("#colorSelector").val();
var selectedABC = $("#colorSelector").find("option:selected").attr('extra-attr');
}

I want ID and Name of html select to have different value

I have dropdown list of countries and states and javascript program uses the ID of country to show only state of that county(dynamic dependence ) but i also want to store selected country and state to another database table.the problem is it's storing the ID value into my new table.currently it stores on ID of selected countries and state rather than names. kindly help out.
Here is the code
<label>Select Country</label>
<select class="browser-default custom-select" name="DestionationCountry" id="DestionationCountry">
<option value="">Select Country</option>
<?php
require_once('DbConnection.php');
$countries = mysqli_query($connection, "SELECT * FROM country ORDER BY country");
while ($country = mysqli_fetch_assoc($countries)) {
echo "<option value='" . $country['id'] . "'>" .
$country['country'] . "</option>";}
?>
</select>
The value that you are sending from your form is stored in value attribute of option tag

Arrays from 2 MySQL queries to be used on 2 select using javascript

I already have the first HTML select populated by the result of the first query.
Now what I need or want to do is put the results from the second query on a Json file (maybe) or an XML (don't care) and then using javascript (not jquery) populate the second HTML select based on the first HTML select option selected.
This is my current code:
<?php
# Get all brands id and brand name to populate brands HTML select 1
$q1=mysqli_query($conect,"SELECT id, brand FROM brands ORDER BY brand ASC");
$brand_select="";
while($brand=mysqli_fetch_assoc($q1)){
$brand_select=$brand_select.'<option value="'. $brand['id'] .'">'. $brand['brand'] .'</option>';
}
# Get all models id and model name to populate models HTML select based on the brands ID from html select 1
$q2=mysqli_query($conect,"SELECT id, brand_id, model FROM models ORDER BY model ASC");
$models_select="";
while($model=mysqli_fetch_assoc($q2)){
$models_select=$models_select.'<option value="'. $model['id'] .'">'. $model['modelo'] .'</option>';
}
?>
<select name="brand" id="brands" class="s1" onchange="populate(this.id,'modelos')">
<option value="">Select Brand</option>
<?= $brand_select ?>
</select>
<br>
<select name="models" id="models" class="s1">
<option value="">Select Model</option>
<?= $models_select ?>
</select>
The id from the brands table is related to the brand_id on the models table for relational purposes.
The brands HTML select are displaying the brands just perfect as it should and the options as is, are showing the full list of models of all brands.
I'm sure that an onChange event should be used on the first HTML select, that is as far as I can get without Javascript.
Of course I've looked other Similar Questions but can't find one that matches my idea about this.
Any suggestion from You the real genius :-)
Here is one way of doing it. PHP is used to produce an array of model options sorted by brand - this makes things easier for the JavaScript. An event listener is added to the brands select which updates the models select appropriately.
PHP
$q1=mysqli_query($conect,"SELECT id, brand FROM brands ORDER BY brand ASC");
$brand_select="";
while($brand=mysqli_fetch_assoc($q1)){
$brand_select=$brand_select.'<option value="'. $brand['id'] .'">'. $brand['brand'] .'</option>';
}
# Get all models id and model name to populate models HTML select based on the brands ID from html select 1
$q2=mysqli_query($conect,"SELECT id, brand_id, model FROM models ORDER BY brand_id, model ASC");
$models_select="";
while($model=mysqli_fetch_assoc($q2)){
$models_select[$model['brand_id']][] = '<option value="'. $model['id'] .'">'. $model['model'] .'</option>';
}
echo "<script type=\"text/javascript\">\nvar models = {};\n";
foreach ($models_select as $b => $m) {
echo "models['$b'] = '" . implode('', $m) . "';\n";
}
echo '</script>';
Javascript
window.addEventListener('load', function () {
document.getElementById('brands').addEventListener('change', function () {
if (this.value != '') {
document.getElementById('models').innerHTML = '<option value="">Select Model</option>' + models[this.value];
}
});
});
HTML
<select name="brand" id="brands" class="s1">
<option value="">Select Brand</option>
<?= $brand_select ?>
</select>
<br>
<select name="models" id="models" class="s1">
<option value="">Select Model</option>
</select>
Easy solution is:
Create a php array with all the models that you then write into a javascript array:
$models = [];
while($model=mysqli_fetch_assoc($q2)){
$models_select=$models_select.'<option value="'. $model['id'] .'">'. $model['modelo'] .'</option>';
$models[] = $model;
}
?>
<script>
var moduls = <?php echo json_encode($models); ?> // this makes a JSON string out of the php array, which js can interpret as javascript array/object.
function populateModels(brandId) {
// TODO:
// filter the models that have the right brandId
// generate the options of the fitting models
// write the options to select #models
}
</script>
A better (because you don't have massive data lying around that you possibly don't use) solution would be to use ajax, as you can find in many questions/answers for "Dynamic selects"

dynamic change of subcategory select options according to option selected in this subcategory

What i have now:
1)31june.html
2)32june.php
I have a table "jewelry" with this structure:
id
brand(varchar)
type(varchar)
model(varchar)
collection(varchar)
description(text)
code(varchar)
url(varchar)
available(int)
First file 31june.html is a select box in which are listed types (earrings,necklace,watches), according to which type we choose the script will send the selected type to second file 32june.php.
32june.php will do another things:
1)query :
$sql='SELECT collection FROM jewelry WHERE type = ?'
2) echo another select box with query($sql) in it.
For example i have chosen in select box earrings, in DB jewelry table will be selected all collection with type earrings and this collection will be displayed in a new select box as an option.
What i want: i need to choose the type then the select box with collection will display according to type then I want to choose the collection in the generated select box and according to it, replace it (this collection name) with another select option or for example with the new result i want to display in this select box.
For example:
Type: earrings -> generated select box with collection option value coll1
I select coll1.
I want coll1 to be replaced with the new date.
<script type="text/javascript">
$(document).ready(function(){
$('#type').on("change",function () {
var chosen= $(this).find('option:selected').val();
$.ajax({
url: "31june.php",
type: "POST",
data: "chosen="+chosen,
success: function (response) {
console.log(response);
$("#ajdiv2").html(response);
},
});
});
});
</script>
<div id="ajdiv">
<select name="type" id="type">
<option>Select Type</option>
<option value="earrings">Earrings</option>
<option value="necklace">Necklace</option>
<option value="watches">Watches</option>
</select>
</div>
<div id="ajdiv2"></div>
<?php
$chosen = $_POST['chosen'];
function mm ($chosen){
$host="xxxx";
$pass="xxxx";
$user="xxxx";
$db="xxxx";
$connect ="mysql:host=$host;dbname=$db";
$pdo = new PDO($connect, $user, $pass);
$sql1='SELECT collection FROM jewelry WHERE type = ?';
$stmt = $pdo->prepare($sql1);
$stmt->execute(array($chosen));
foreach($stmt as $val){
$select = '
<select name="users" id="yol" onchange="showUser(this.value)">
<option value="">Select Collection:</option>
<option value="collection">
' . $val['collection'] . '</option>
</select>';
echo $select;
}
}
echo mm($chosen);
It might be an issue with your loop, you are creating multiple select elements. Try changing to :
$select = '
<select name="users" id="yol" onchange="showUser(this.value)">
<option value="">Select Collection:</option>
';
foreach($stmt as $val){
$select = $select . '
<option value="collection">
' . $val['collection'] . '</option>';
}
$select = $select . '</select>';
echo $select;
Then you can implement showUser(), or create another change handler for it instead like you have for type.

Retrieve data from MySQL according to the item_ID selected from the select box

I have a populated MySql database, my database has two columns (item_ID, item_title), and my HTML page has a select box, where all the item_IDs are stored, and below it I have a input box, now I want to do the following:
When the user selects an item_ID from the select box, it should go to the database and find out what is the item_title that belongs to that item_ID.
I am currently using PHP, I don't know how to carry such task.
Thank you in advance.
NB: I am okay populating the select box with all the available item_IDs. The only thing I am not sure how to implement is to retrieve the item_title dynamically as the item_ID changes, and display inside input box.
<select name='item_ID'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input name='item_title' value='Should change as the item_ID changes' />
Let's say you generate your select element dinamically with PHP:
<?php
while($row = mysql_fetch_assoc($some_query)) {
echo "<option>" + $row["id"] + "</option>";
}
?>
Right? But now why not add the title in the same query and generate the select with it?
echo "<option data-title='" + $row["title"] + "'>" + $row["id"] + "</option>";
Nice, so your select will looks like:
<select name='item_ID'>
<option data-title="Title 1">1</option>
<option data-title="Title 2">2</option>
<option data-title="Title 3">3</option>
<option data-title="Title 4">4</option>
</select>
Now you bind a change event to the select like this:
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
Don't forget to add id="item_title" to your title field.
So, with this approach you won't need an extra request and extra query to database in order to get the title by adding it in the same query that you use to create the select(with inner/left join if its from another table, I think). Thus, it will increase your application performance.
UPDATE:
The event binding should stay on the ready event of the document, like this:
$(document).ready(function() {
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
});
And for more columns you just add them with data- prefix to the option element attributes:
<option data-title="" data-other-property=""></option>
And so on... Then to access it you use the same method:
$(selectedOption).data("title");
$(selectedOption).data("other-property");
Considering selectedOption stands for the option element.
Some references the worth a reading:
Using data attributes # MDN
$(document).ready() # jQuery Learning Center

Categories

Resources