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

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

Related

2 Conditional dropdown in codeigniter

District Master table:
District table:
District Master
District
I have a form page in which there is a drop down called Category, In my district table i have district code saved and Category name. Based on the Category drop down selection in need to display district names present in District Master Table.... I'm Able to populate drop down, But when I do this I'm getting the district codes not the District Name....Somebody Please help!!!
My View Page:
<select name="category" id="category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<select name="placename" id="placename">
<option value="">Please select a Place</option>
</select>
Controller:
public function ajax_place_list()
{
$this->load->helper('url');
$this->load->model('JcMeetingExpense_model');
$data['district'] = $this->JcMeetingExpense_model->getplace();
echo json_encode($data);
}
Model:
function getplace()
{
$this->db->where('district_code',$this->input->post('category'));
$query = $this->db->get('district');
return $query->result();
}
Script
<script>
jQuery(document).ready(function($) {
$("#category").on('change', function() {
var category= $(this).val();
if(category){
$.ajax ({
type: 'POST',
url: 'JcMeetingExpense/ajax_place_list',
data: { category: category},
success : function(response) {
var response = $.parseJSON(response);
$('#placename').val(response.district);
},error:function(e){
alert("error");}
});
}
});
});
</script>
i think in district table column (district) similar to district master table column (district_code) then
use inner join with district master table in model
$this->db->select('*');
$this->db->from('district');
$this->db->join('District_Master', 'district.district= District_Master.district_code');
$this->db->where('district.district_code',$this->input->post('category'));
$query = $this->db->get();
using this query you can get name from district_master table and you can used name in dropdown
you can simply use ajax to get district name just and an listen even like on change or blur on the catagory drop down when you get the values from db for example you have used a query like this in model part
function getplace()
{
$this->db->where('district_code',$this->input->post('category'));
$this->db->join('District_Master', 'district.district= District_Master.district_code');//added this
$this->db->select("District_Master.district_name");//add this
$this->db->from("district");
$query = $this->db->get();
return $query->result();
}
then for the dropdown of district use
<select><option value="//call district_code here "> //call district_name here</option></select>
call the above thing with your object since you said that you have populated the data in dropdown this can be one of the error try and comment if any error

Javascript dynamic dropdown options duplicate

I have 2 dynamic dropdown lists namely Levels and Grades that can also do multi-select. “Grades” dropdown changes its values whenever I choose an option in “Levels” dropdown. If I select High School in “Levels” dropdown, then the “Grades” dropdown values will now be grades 7-10. Now, the problem is, if I select Kinder in “Levels” dropdown while High School has been previously selected, “Grades” dropdown values like Kinder and Prep duplicates. That’s not the only situation where duplicate is happening. The same thing happens when I deselect either one or both in “Levels” dropdown.
Here's my screenshot:
image
Here are my codes:
* I am using select2 plugin for my dropdown lists
HTML - send_sms_non.blade.php
//Levels dropdown list
<select multiple="multiple" class="form-control select2meAdd selectelement" required id="levels" name="levels[]" style="width:50%;">
<option value="" selected disabled></option>
#foreach ($data['stages'] as $stage)
<option value="{{ $stage->id }}">{{ $stage->stage }}</option>
#endforeach
</select>
//Grades dropdown list
<select multiple="multiple" class="form-control select2meAdd selectelement" required id="grades" name="grades[]" style="width:50%;">
</select>
PHP
public function getIndexNon()
{
if (!(require_school_access('ACCESS-SMS', 4))) {
return redirect('/home/invalid-access');
}
$data['subscription'] = $this->subscription;
$data['schoolfront'] = $this->schoolfront;
$data['accounts'] = SchoolAccount::where('school_id',$this->subscription->subscription->id)->get();
$data['stages'] = SchoolStages::where('school_id',$this->subscription->subscription->id)->get();
return view('school.send_sms_non', array('data' => $data));
}
public function getAjaxDataGrades(Request $request)
{
$level_ids = explode(',', Input::get('level_ids'));
// $selected_levels = array();
// foreach ($level_ids as $level_id) {
// if ($level_id) {
// if (!in_array($level_id,$selected_levels)){
// $selected_levels[] = $level_id;
// }
// }
// }
$grades = SchoolStages::leftJoin('school_stage_levels','school_stage_levels.stage_id','=','school_stages.id')
->whereIn('school_stage_levels.stage_id',$level_ids)
->where('school_stages.school_id',$this->subscription->subscription->id)
->get();
return Response::json($grades);
}
JAVSCRIPT
$('.select2me').select2();
$('#levels').on('change',function(){
var level_ids = $(this).val();
$.get('/sms/ajax-data-grades?level_ids='+level_ids, function(data){
// $('#grades').empty();
$('#grades').append('<option value="0" selected disabled>
</option>');
$.each(data, function(index, gradeObj){
$('#grades').append('<option
value="'+gradeObj.id+'">'+gradeObj.level_code+'</option>');
});
});
});
Thank you very much.
In .each function, you may use the following code to detect whether the incoming item existed in grades down drop box already.
var grades=$('#grades');
var allOptions=grades.children('option');
option = allOptions.find("[value='"++gradeObj.id+"']");
if (option.length==0) //that mean does not exist
{
$('#grades').append('<option
value="'+gradeObj.id+'">'+gradeObj.level_code+'</option>');
}

PHP Adding dynamic category realtime

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

Working with Select options coming from database

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.

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