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
Related
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 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"
I'm making this project on site where there are list of items and they have id and there are another set of data with the same id as the first one and they each have their id. So I want to show options by getting the id of first one to display other realtime with JQuery or JScript and PHP. My code looks like this
Categories are
1. Electronics
2. Venues
And Subcategories are for electronics
Electronics
Hardware Software
Venues
My House
Friends House
<select name="category" id="catagoryid">
<?php
$categories = selectAllData('categories');
while ($row = mysqli_fetch_assoc($categories)) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<option value='{$cat_id}'>{$cat_title}</option>";
}
?>
</select>
And the another set is here
<select name="subcategory" id="subcategory">
<?php
$subcategories = selectAllData('subcategories');
while ($row = mysqli_fetch_assoc($subcategories)) {
$cat_id = $row['cat_id'];
$sub_cat_id = $row['sub_cat_id'];
$sub_title = $row['sub_cat_title'];
echo "<option value='{$sub_cat_id}' title='{$cat_id}'>{$sub_title}</option>";
};
?>
</select>
So far I what I have tried are
$('#subcategory').change(function(event) {
var subcategory = $(this).find('option:selected').attr("title");
if (subcategory!==categoryid) {
if ($(this).find('option:selected').val()!==categoryid) {
$(this).find('option:selected').hide();
}
}
});
And other approach I have been stuck here from yesterday. I have tried getting value of selected item from JavaScript and running php. But I noticed that php loads before Jscript so there is no way to do this way. There was another approach of running Jscript inside PHP but I couldn't get the value if user selects another item.
One way is remove and store all the subcategory <option> on page load.
Then clone and filter the stored <option> and replace what is in the second select when the first is changed.
You can use classes or data attributes as filters
//remove and store subcategory options
var $subCatOpts = $('#subcategory option').detach();
$('#catagoryid').change(function() {
var catId = this.value;
// clone stored ones so we always have them available...then filter
var $opts = $subCatOpts.clone().filter(function() {
return !this.value || catId === $(this).attr('data-catid')
});
$('#subcategory').html($opts)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Category:
<select name="category" id="catagoryid">
<option value=""> -- Select Category -- </option>
<option value="1">Electronics</option>
<option value="2">Venues</option>
</select>
Subcategory
<select name="subcategory" id="subcategory">
<option value=""> -- Select Sub category -- </option>
<option value="1" data-catid="1">Electronics - Sub 1</option>
<option value="2" data-catid="1">Electronics - Sub 2</option>
<option value="3" data-catid="2">Venues - Sub 1</option>
<option value="4" data-catid="2">Venues - Sub 2</option>
</select>
Pass all the data on page load to browser.
<?php
$subcategories_json = array();
$subcategories = selectAllData('subcategories');
while ($row = mysqli_fetch_assoc($subcategories)) {
$subcategories_json[] = array(
'cat_id' => $row['cat_id'],
'sub_cat_id' => $row['sub_cat_id'],
'sub_title' => $row['sub_cat_title']
);
}
echo "<script>subcategories = ".json_encode($subcategories_json).";
</script>";
?>
Then in Javascript (something similar to this):
$(...).change(function(event) {
var subcategory_title = $(this).find('option:selected').attr("title");
for(k in subcategories)
{
if (subcategory_title==subcategories[k].id) {
$(this).append('<option>'+subcategories[k].name+'</option>')
}
}
});
You can solve this one using ajax, Call ajax - on change event of category select box. See Below link that describe dynamic category implementation:
jQuery ajax unlimited dynamic selectbox based on parent categories
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.
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.