PHP Adding dynamic category realtime - javascript

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

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');
}

Filter Dropdown Based on Other Dropdown Selection

I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
This is the JavaScript that I have so far, however, if I do a console.log(classN), all that it is doing is just logging all of the dates. It doesn't actually filter anything:
$(document).ready(function () {
var allOptions = $('#date option')
$('#collector').change(function () {
$('#date option').remove();
var classN = $('#collector option:selected').prop('class');
var opts = allOptions.filter('.' + classN);
console.log(opts);
$.each(opts, function (i, j) {
$(j).appendTo('#date');
});
});
});
jquery can't run php on the page once it is loaded. You could use ajax, running the query to get the second set of options from another file.
<select id="collector">
<?php //code to generate initial collector options ?>
</select>
<select id="date">
<option>--Bill Date--</option>
</select>
In your jquery, target the first dropdown and then use load() to call a php file
$(document).ready(function(){
$("#collector").on('change', function(){
filterItems(this.value);
});
});
function filterItems(value){
var destination = "#date";
var url = "path/to/filterCode.php?v="+value;
$(destination).load(url);
});
In the filterCode php file, get the value selected by the user
$selectedCollector = $_GET['v'];
Then use $selectedCollector to query your database and get the appropriate date options.
Then, inside your results loop:
echo '<option class="'.$date['Date'].'" value="'.$date['Date'].'">'.$date['Date'].'</option>';
The load() will take these echoed options and put them into #date.
I think you need to populate #date drop-down based on #collector drop-down value, according to me best option is ajax.
here some basic example,
<select id="collector">
<option value=""></option>
</select>
jut think this as your #collector drop-down there will be some options based on your data. Now you need to populate #date drop-down,
<select id="collector">
<option value=""></option>
</select>
In page load you can load all the data if you want.
when #collector drop-down change you can send ajax request and retrieve data from database based on #collector value, like this
$("#collector").on('change', function(){
$.ajax({
type: method,
url: url,
data: data,
success: function(response) {
//populate select box
}
});
});
Below links will be helpful,
How to Use jQuery’s $.ajax() Function
Populate dropdown select with array using jQuery

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.

dropdownlist redirect remember chosen option

I need to have a dropdownlist that contains some parameters for the url on the change event. So when you select an option from the list it will redirect you to the same page with some extra parameters to query the data. The problem is when you change dropdownlist it doesn't remember it's selected option could someone show me how to have a dropdowlist show the selected option across url changes.
<script tpye="text/javascript">
$(function() {
$('#sort_by').on('change', function(e) {
window.location.href + $(this).val();
})
})
</script>
<select id="sort_by" name="sort_by">
<option>Sort By</option>
<option value="&sort_by=title&direction=asc">Title ASC</option>
<option value="&sort_by=title&direction=desc">Title DESC</option>
<option value="&sort_by=created_date&direction=asc">Created Date ASC</option>
<option value="&sort_by=created_date&title=asc">Created Date DESC</option>
</select>
i have added an extra parameter in query string 'chosen' to make the dropdown remember its selected value.
$option[0] = array('value'=>'','title'=>'Sort By');
$option[1] = array('value'=>'?sort_by=title&direction=asc&chosen=1','title'=>'Title ASC');
$option[2] = array('value'=>'?sort_by=title&direction=desc&chosen=2','title'=>'Title DESC');
$option[3] = array('value'=>'?sort_by=created_date&direction=asc&chosen=3','title'=>'Created Date ASC');
$option[4] = array('value'=>'?sort_by=created_date&title=asc&chosen=4','title'=>'Created Date DESC');
<select id="sort_by" name="sort_by">
<?php foreach($option as $key=>$val){
$a = ""; if($_GET['chosen']==$key){$a = 'selected="selected"';}
echo '<option '.$a.' value="'.$val['value'].'">'.$val['title'].'</option>';
} ?>
</select>
Hope it might help.

Dynamically populated select lists

I have 2 select lists and I would like to populate the options in the 2nd list based on the selection of the first list.
This is the first list:
<select class="" id="applicationForm_package">
<option value="no_package">Please select a package</option>
<option package_identifier="package_5" value="5">Package 1</option>
<option package_identifier="package_60" value="60">Package 2</option>
<option package_identifier="package_58" value="58">Package 3</option>
<option package_identifier="package_55" value="55">Package 4</option>
</select>
I then have (in javascript) and variable for each package in the first list:
<script>
var package_5 = "<option value='20'>1 Month</option><option value='110'>6 Months</option><option value='200'>12 Months</option>";
var package_60 = "<option value='25'>1 Month</option><option value='140'>6 Months</option><option value='250'>12 Months</option>";
var package_58 = "<option value='26'>1 Month</option><option value='146'>6 Months</option><option value='270'>12 Months</option>";
var package_55 = "<option value='37'>1 Month</option><option value='212'>6 Months</option><option value='400'>12 Months</option>";
</script>
As the user interacts with the first select list, I would like the options from the respective variables to populate the 2nd list.
Below is the 2nd select and the javascript that I have written. Everything seems to work fine, the issue is the 2nd select list is not getting updated. In my else statement, the console is working but the variable is not defined when I check it in my console.
<select id="applicationForm_subscription">
<option value="no_package_selected">Please select a package First</option>
</select>
<script>
var noPackageSelected = "<option value='no_package_selected'>Please select a package</option>";
jQuery( "select#applicationForm_package" ).change(function() {
var package_name = jQuery( "select#applicationForm_package option:selected").text();
var package_id = jQuery( "select#applicationForm_package option:selected").val();
if(package_id == "no_package"){
jQuery("select#applicationForm_subscription").find("option").remove().end().append(noPackageSelected).val("no_package_selected");
}else{
console.log("update subscriptions");
var get_selected_package_name = jQuery("select#applicationForm_package option:selected").attr('package_identifier');
jQuery("select#applicationForm_subscription").find("option").remove().end().append(get_selected_package_name);
}
});
Any assistance would be great.
Cheers,
Your code is messy for such a simple task as conditionally changing the innerHTML of an element.
A few things to note:
$ is a short-hand for jQuery
you can use $('select').val() to get the value of the selected option
it is redundant to use tag#id for identification, #id is both faster and shorter
If I understand you right, you want to:
listen to the change event of a (first) select,
see if its value is appropriate,
populate a second list based on selection from the first.
I recommend using an Object to store the markup for the second list - so that it would be more straightforward to only store a package ID in each option of the first list:
HTML
<select class="" id="applicationForm_package">
<option value="5">Package 1</option>
<option value="60">Package 2</option>
<!-- ... -->
</select>
... and then set the second list's innerHTML using that ID with a string from the packages object:
JavaScript
var packages = {
5: "<option value='20'>1 Month</option><option value='110'>6 Months</option><option value='200'>12 Months</option>",
60: "<option value='25'>1 Month</option><option value='140'>12 Months</option><option value='250'>24 Months</option>",
58: "<option value='26'>1 Month</option><option value='146'>2 Months</option><option value='270'>4 Months</option>",
55: "<option value='37'>1 Month</option><option value='212'>4 Months</option><option value='400'>8 Months</option>"
};
$('#applicationForm_package').change(function () {
// see if there is listing for this package ID
if (packages.hasOwnProperty($(this).val()))
{
// List options
$('#applicationForm_subscription').html(packages[$(this).val()]);
}
else
{
// Please select a package First
$('#applicationForm_subscription').html('Please select a package First');
}
});
Working example on JSFiddle.
If you want dynamicaly get the content of the variable based on name then you should use this:
jQuery("select#applicationForm_subscription").find("option").remove().end()
.append(window[get_selected_package_name]);

Categories

Resources