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
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 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
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
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.
In my database I have two related fields. The second field depends on the value selected in the first. The relations are:
The function I use in the form of table "conflictos_1" is:
<!--Aquí el javascript para select dependientes-->
<script type="text/javascript">
$(document).ready(function()
{
$("#conflictos1_id_sector_actividad").change(function()
{
var id_sub = $(this).val();
if(id_sub != '')
{
$.ajax
({
type: "POST",
url: '<?php echo url_for('conflictos/subsector'); ?>'+ '?id=' + id_sub,
cache: false,
data: "id_sub="+ id_sub,
success: function(data)
{
$("#conflictos1_id_subsector_actividad").html(data); // but it does not select the value of dropdown list.
}
});
}
else
{
$("#conflictos1_id_subsector_actividad").html("<option value=''>-- No se ha seleccionado subsector --</option>");
}
return false;
});
});
</script>
When I add a new record, everything works fine.
But when I edit a record, the select dependent, does not show "selected" value.
In edit mode, when I look at the field "id_subsector_actividad", the selected value should be, for example, <option value="37 " selected="selected">: This is what I see on my form when I inspect the element created with AJAX's function:
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="29 ">14.1 Meretrices</option>
<option value="30 ">Preparación de alimentos y comedor</option>
<option value="31 ">Seguridad</option>
<option value="37 ">redes sanitarias</option>
</select>
This is what I WANT to see:
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="29 ">14.1 Meretrices</option>
<option value="30 ">Preparación de alimentos y comedor</option>
<option value="31 ">Seguridad</option>
<option value="37 " selected="selected">redes sanitarias</option>
</select>
I use this function to filter records in the table "Subsector_actividad_ta8"(I work with Symfony 1.4 and Doctrine):
public function executeSubsector()
{ $id_sub = $_POST['id_sub'];
$this->subsec= Doctrine_Core::getTable('SubsectorActividadTa8') ->createQuery('a')
->where('a.id_sector = ?', $id_sub)
->execute();
}
My question is: What should I change in the AJAX's function, to display the "selected" value in the second field, when I am editing an existing record?
Maybe with something like:
$("option[value='37']").attr('selected', 'selected');
You have a similar question on: Set selected option of select box
Here the solution I encountered: I've separated the problem in two.
Case 1: New Record
I use the same JQuery function shown above in the question. With the associated function, also shown above. This case was not part of my problem
Case 2: Edit an existing record (here was my problem)
I added for 'id_subsector_actividad' in the widget the property 'table_method'=>'Subsector' associated with the function public function Subsector() (see below code).
In the partial _form.php of conflictos1, I wrote the following code for the field id_subsector_actividad:
<?php if (!$form->getObject()->isNew()): ?>
<?php echo $form['id_subsector_actividad'] ?>
<?php endif; ?>
<?php if ($form->getObject()->isNew()): ?>
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="" selected="selected">Seleccione sub-sector</option>
<?php endif; ?>
In the action.class.php in the conflictos1, I modified the function executeEdit, with the addition of the variable $elsector:
public function executeEdit(sfWebRequest $request)
{
global $elsector;
$this->forward404Unless($conflictos1 = Doctrine_Core::getTable('Conflictos1')->find(array($request->getParameter('id'))), sprintf('Object conflictos1 does not exist (%s).', $request->getParameter('id')));
$elsector= $conflictos1->getIdSectorActividad();
$this->form = new Conflictos1Form($conflictos1);
}
I use $elsector in the following function created in SubsectorActividadTa8Table.class.php
public function Subsector()
{
global $elsector;
if (!is_null($elsector)){
$id_sub=$elsector;
$query= Doctrine_Query::create()
->select('a.id')
->from('SubsectorActividadTa8 a')
->innerJoin('a.Conflictos1 c')
->where('a.id_sector = ?', $id_sub);
return $query->execute();
}
}
Thus, Symfony displayed on the form, the value of field named IdSubsectorActividad, not previously exhibited.
In other words, now when I'm editing a record in the table conflictos1 the field named IdSubsectorActividad shows the correct value, whereas before the form does not show any value.
Now everything works fine!.