I have two dropdowns which full information from my SQL table. One dropdown consist of "Colors." The other dropdown consist of members in the specific colors. I already have them in the different optgroup based on their class value which is "color."
My goal is to have the user select "COLOR" and only the members in that class show up in the member dropdown.
Ex. I select Red on the first dropdown. Only members in "Red" will be available in the second dropdown.
Hopefully it can be down using JavaScript
SQL Table:
+-----------+--------------+
| GroupName | MemberName |
+-----------+--------------+
| Red | Joe Bob |
| Red | Catherine |
| Blue | Tommy |
| Orange | John Razks |
| Black | Trevor Smith |
+-----------+--------------+
+--------+
| Color |
+--------+
| Red |
| Blue |
| Orange |
| Black |
+--------+
PHP Code:
<?php
$conn = mysqli_connect("#Connecting");
if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
else{
$color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
$colors = array();
while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
$member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName from Members order by MemberName ASC");
$members = array();
while ($row = mysqli_fetch_assoc($member_result)){
if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
$members[$row['GroupName']][] = $row; }
}
?>
<form id=#blah>
Color:
<select id="committee" name="committee">
<option value="">Select Color</option>
<?php
foreach($colors as $color){
echo "<option value=\"".$color."\">".$color."</option>";
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
foreach($members as $key => $member_group){
echo "<optgroup class=\"".$key."\">";
foreach($member_group as $val){
echo "<option value=\"".$val['MemberName']."\">".$val['MemberName']."</option>";
}
echo "</optgroup>";
}
?>
</select>
</div>
</form>
<form id=#id>
Color:
<select id="committee" name="committee">
<option value="">Select Color</option>
<?php
foreach($colors as $color){
echo "<option value=\"".$color."\">".$color."</option>";
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
foreach($members as $key => $member_group){
echo "<optgroup class=".$key.">";
foreach($member_group as $val){
echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
}
echo "</optgroup>";
}
?>
</select>
</form>
you can use this demo code which help you
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="firstmenu" name="City" onchange="select_other(this.value)">
<option value="Color1">Color1</option>
<option value="Color2">Color2</option>
<option value="Color3">Color3</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
<option value="Color1">Member1</option>
<option value="Color2">Member2</option>
<option value="Color3">Member3</option>
</select>
<script>
function select_other(value){
$("#secondmenu").children('option').hide();
$("#secondmenu").children("option[value^=" + value + "]").show();
$("#secondmenu").children("option[value^=" + value + "]").attr('selected',true);
}
</script>
What would work is to fill the values of an option with the members and read them out in a new select, but it's easier with an example:
HTML & PHP CODE
Of course you can still use your array, but I just like to do it with the "while($fetch = mysqli_fetch_assoc($query))" way. Also It surely doesn't look nice, but that's not part of the question ;)
// on the color select add this onchange
<select id="color" onchange="setOptions(this.value)">
<?php
$color_result = mysqli_query($conn, "SELECT * from color ");
while ($fetch_colors = mysqli_fetch_assoc($color_result)) {
$color = $fetch_colors['color'];
// This select is changed: WHERE GroupName='$color',
// so it just reads the members of the current color
$member_result = mysqli_query($conn, "SELECT distinct MemberName from Members WHERE GroupName='$color' order by MemberName ASC");
$memberstring = "";
$i=1;
$count_rows = mysqli_num_rows($member_result);
// Here just an string gets filled which will be the value of the option
while ($fetch_member = mysqli_fetch_assoc($member_result)) {
if ($count_rows==$i) {
$memberstring.=$fetch_member["MemberName"];
} else {
$memberstring.=$fetch_member["MemberName"].",";
$i++;
}
}
// This is the option with the color and with the value as members
echo "<option value=\"$memberstring\">".$color."</option>";
}
?>
</select>
<select id="members">
// In here the options will show up
</select>
JAVASCRIPT CODE
So this is a pretty much simplified version of the javascript. Meaning, it just runs on every change of the color option. If you want to have a "clear" option you will have to 1. insert it into the select (also add a special value) 2. write an if in the javascript function, to check if the option is clear.
function setOptions(val) {
val = val.split(","); // val is now an array with all the members of the color
document.getElementById('members').innerHTML = ""; // This clears all "old" members of the select
var select = document.getElementById("members");
for (var i = 0; i < val.length; i++) { // Now for each Member in the array a new Option is created
var option = document.createElement("option");
option.text = val[i];
select.add(option);
}
}
More links:
javascript add option,
removing all options
If you have any questions, feel free to ask me in the comment section.
Related
I am using laravel 5.2 and javascript. I have an update form which contain a dropdownlist which I call using ajax with function getTugasDetailUpdate . My problem is how can I set the value from the database and make the dropdownlist selected the value from the database that I have chosen before? This below is my code in the controller.
public function getTugasDetailUpdate(Request $request)
{
$update_tugas_id = $request->get("V_ID_PK");
$getDataListPengikut = DB::select("EXEC dbo.GET_KEMENPAR_LIST_PENGIKUT '".$update_tugas_id."'");
$getPengikut2 = DB::select("EXEC dbo.LOV_M_PENGIKUT");
$msg["opt"] ="";
$no=1;
foreach($getDataListPengikut as $dtListPengikut):
$msg["opt"] .= '<tr>
<td><select class="form-control" id="name_'.$dtListPengikut->KODE.'" name="nameupdate[]" data-live-search="true" style="width:100%">
<option value=""> --Silahkan Pilih-- </option>';
foreach ($getPengikut2 as $getPeng){
$msg["opt"] .= '<option value="'.$getPeng->KODE.'">'. $getPeng->DESKRIPSI .'</option>';
}
$msg["opt"] .='</select>
</td>';
$msg["opt"] .= '</tr>';
$no++;
endforeach;
echo json_encode($msg);
}
And how can I get a value from those controller and set it in my javascript? I want to make var optionS = $('#name_3').html(); has an id same like id="name_'.$dtListPengikut->KODE.'" ? those #name_3 is a hardcode, it could be name_4, name_2, etc.
var i=1;
function addMe(e){
var optionS = $('#name_3').html();
i++;
$('#dynamic_field_update').append('<tr id="row'+i+'" class="dynamic-added"><td><select class="form-control" id="name_3" name="nameupdate[]" data-live-search="true" style="width:100%">'+optionS+' </select></td></tr>');
}
You should separate your HTML from your application logic. I suggest you use Laravel Collective package, here is a minimal example:
#foreach($getDataListPengikut as $dtListPengikut) {
Form::select('XXXXXXXX_name', //Unique name for select
['key' => 'value', 'key2' => 'value2'], //Options for this select
null, //Default option (selected)
[
'placeholder' => 'Pick something', //Classes applied to select
'data-live-search' => 'true',
'style' => 'width:100%'
]
);
#endforeach
We have e commerce shopping site with many products.
We have lot of Designers , each Designer is owner of multiple products.
We are displaying Designers in dropdown , once we select Designers , than we can select Orders of those Designers , once we select Orders, than we can select related products.
Basically we are selecting all 3 dropdown fields and submitting form and saving values in database.
1. If order contains products of only one designer , after we select those products and submit form, than again if we select same Designer , previously selected Order will not visible. Thats fine.
Ex: here you can see we selected "kidsdial2" as Designer and order "100000142" and submit form
so when we select "kidsdial2" next time, we can't see order "100000142"
2. If order contains products of only multiple designers , after we select those products and submit form, than again if we select same Designer previously selected Order is Still visible. But we want to hide "Order" here also. this is the issue.
Ex : here order "100000141" contains products of multiple designers. so we selected Designer "kidsdial2" & order "100000141" and selected products and submit form.
when we select "kidsdial2" next time, we don't want to see order "100000142".
html
<form action="update_paidstatus.php" id="" onsubmit="return validate(); ">
<select onchange="getOrderDetail(event);" name="designer_id" id="designer_id">
<option value="">Select Designer</option>
<?php
while($data = $stmt->fetch())
{
if($data['type']=="admin")continue;
?>
<option value="<?php echo $data['userID'];?>">
<?php
echo $data['name'];
?>
</option>
<?php } ?>
</select>
<div id="ordernumbers">
<select name="designerorder_id" id="designerorder_id" class="designerorder_id" onchange='getProductDetail(this.value)'>
<option value="">Select Order</option>
</select>
</div>
<div id="productnumbers" name="dproduct_id" id="dproduct_id">
<select id="mySelect">
<option>Select Products</option>
</select>
</div>
</form>
script
function getOrderDetail(e)
{
var designerId=e.target.options[e.target.selectedIndex].value;
var url="http://sbdev2.kidsdial.com:81/php/site6/designerpaidstatus.php?designer_id="+designerId+"&opration=2";
var request = jQuery.ajax( {
url: url ,
type: 'POST',
} );
request.done( function (result)
{
//document.getElementById('ordernumbers').innerHTML =result;
$(".designerorder_id").html(result);
} );
request.fail( function ( error )
{
console.dir(error);
} );
}
php
require_once '../../app/Mage.php';
Mage::app();
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id',array('like' => '%'.$id.'%'));
$htmltext='<select>';
$htmltext.="<option value=''>Select Order</option>";
foreach ($order as $orderData)
{
$data=array();
$sqlq1="select dproduct_id from order_details where designer_id='".$id."' and designerorder_id='".$orderData->getIncrementId()."'";
$sqlq=mysqli_query($conVar,$sqlq1);
while($rdata=mysqli_fetch_assoc($sqlq))
{
$data[]=$rdata['dproduct_id'];
}
$orderitems=$orderData->getData('dproduct_id');
$oitem=explode(',',$orderitems);
$finalValue=$orderData->getIncrementId()."-".$orderitemsarray[$k];
$result=array_diff($oitem,$data);
$result1=implode(',',$result);
if(count($result)>1)
{
$result2=array();
foreach($result as $product)
{
$_product = Mage::getModel('catalog/product')->load($product);
$_productDesignerId = $_product->getDesignerId();
if(trim($_productDesignerId) == trim($id))
{
$result2[] = trim($product);
}
}
$result2=implode(',',$result2);
$htmltext=$htmltext.'<option class="'.$result2.'" name="'.$result2.'" value="'.$orderData->getIncrementId().'">'. $orderData->getIncrementId().'</option>';
}
}
$htmltext=$htmltext."</select>";
echo $htmltext;exit;
sample database :
Edit - update_paidstatus.php
$newURL="http://sbdev2.kidsdial.com:81/php/site6/paidstatus.php";
if(isset($_POST) && $_POST!="" && !empty($_POST)){ // checking if form submision is occured or not.
$sucessFlag=true;
$productIds=explode(",",$_POST['dproduct_id']);
$oDate = new DateTime($_POST['dueDate']);
$sDate = $oDate->format("Y-m-d");
if(isset($conVar) && !empty($conVar) && $conVar!="")
{
for ($i=0; $i< count($productIds); $i++) {
$sqlQueryToUpdate="INSERT INTO order_details ( designer_id,designerorder_id,dproduct_id,dpaid_status,delivery_status,due_date) VALUES('".$_POST['designer_id']."','".$_POST['designerorder_id']."','".$productIds[$i]."','".$_POST['PaidStatus']."','".$_POST['PaidStatus']."','".$sDate."')";
$sucessFlag=mysqli_query($conVar,$sqlQueryToUpdate);
if($sucessFlag==TRUE)
{
echo "UPDATE SUCESSFULLY";
}
else
{
echo " not done.";
}
}
header('Location: '.$newURL);
}
}
?>
Consider there are two designers D1 and D2.
Products P11 and P12 belongs to D1 and products P21 and P22 belongs to D2
Now there is an order O1 which has products P11 and P22
Check the inline comments.
// fetches all order for the particular designer. Try to use = condition rather than like if possible.
// So as per our eg; If Desginer = D1 then it will return O1
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id',array('like' => '%'.$id.'%'));
$htmltext='<select>';
$htmltext.="<option value=''>Select Order</option>";
foreach ($order as $orderData)
{
$data=array();
// Will fetch the product id based on the designer id and desginer order id
// So in our eg: It will return only P1 since P2 is linked to D2
$sqlq1="select dproduct_id from order_details where designer_id='".$id."' and designerorder_id='".$orderData->getIncrementId()."'";
$sqlq=mysqli_query($conVar,$sqlq1);
while($rdata=mysqli_fetch_assoc($sqlq))
{
$data[]=$rdata['dproduct_id']; //P1
}
$orderitems=$orderData->getData('dproduct_id');
$oitem=explode(',',$orderitems); // [P1,P2]
$finalValue=$orderData->getIncrementId()."-".$orderitemsarray[$k];
$result=array_diff($oitem,$data); //P2
$result1=implode(',',$result);
if(count($result)>1)
{
$result2=array();
foreach($result as $product)
{
$_product = Mage::getModel('catalog/product')->load($product);
$_productDesignerId = $_product->getDesignerId();
if(trim($_productDesignerId) == trim($id))
{
$result2[] = trim($product);
}
}
$result2=implode(',',$result2);
$htmltext=$htmltext.'<option class="'.$result2.'" name="'.$result2.'" value="'.$orderData->getIncrementId().'">'. $orderData->getIncrementId().'</option>'; //order data gets appended
}
}
$htmltext=$htmltext."</select>";
echo $htmltext;exit; //order id with P2
How can I have to values at once from select options through JavaScript function?
Here is my code:
<select name="ledger" id="ledger" onchange="setDebit(this.value)" required>
<option value="" >Select</option>
<?php
$ledgerResult = $this->db->query('SELECT * FROM ledger WHERE account_type = "Creditors" ORDER BY name');
$ledgerData = $ledgerResult->result();
for ($c = 0; $c < count($ledgerData); ++$c) {
$ledger_id = $ledgerData[$c]->id;
$ledger_name = $ledgerData[$c]->name;
$ledger_credit = $ledgerData[$c]->credit; ?>
<option value="<?php echo $ledger_id;?>"><?php echo $ledger_name;?></option>
}
</select>
<script>
function setDebit(ele){
document.getElementById("set_debit").value = ele;
}
</script>
I am getting $ledger_id and sending this value through setDebit() to the script. But what I need is to send $ledger_credit. I can do it by setting it as option value instead of $ledger_id; but I also need value of selectas $ledger_id.
How can I set $ledger_id as option value, but send $ledger_credit through setDebit(this.value)?
<option value="<?php echo $ledger_id.":".$ledger_credit;?>"><?php echo $ledger_name;?></option>
function setDebit(ele){
var Value = document.getElementById("ledger").val();
var Parts = Value.split(":");
var LedgerID = Parts[0];
var LedgerCredit = Parts[1];
}
If you are not using jquery.
<option value="<?php echo $ledger_id."||".$ledger_credit; ?><?php echo $ledger_name;?> </option>
<script>
function setDebit(){
var details = document.getElementById("ledger").value;
var allData = details.split("||");
var ledger_id = allData[0];
var ledger_credit = allData[1];
console.log(ledger_id);
console.log(ledger_credit);
}
</script>
You have to set the attribute multiple in the HTML part:
http://www.w3schools.com/tags/att_select_multiple.asp
After that you can have a look at this question for further info:
How to get all selected values of a multiple select box using JavaScript?
You can add an atribute data-credit in yours options
<option value="<?php echo $ledger_id;?>" data-credit="<?php echo $ledger_credit;?>"><?php echo $ledger_name;?></option>
And in the setDebit function:
var ledger_credit = $('option:selected', "#ledger").data('credit');
You must use jquery in this solution
I am new in PHP and JS. This function use to get only one vales.
In my program dept1 values are 5 and 1st value select onchange in 1, 2nd select onchange in 2, 3rd value select onchange in 3. so any idea to give code for switch case.
<script>
function deptchange()
{
var x = document.getElementById("dept1").value;
document.getElementById("dept2").value = 2;
}
</script>
<input class="form-last-name form-control" id= 'dept1'
onchange="deptchange()" list="dept" value='<?php echo $dept; ?>' name="department"/>
<datalist id="dept">
<option>
<?php
include 'dblayer.php';
$query = mysqli_query($mysqli,"SELECT department FROM department");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['department']."'>".$row['department'] .'</option>';
}
?>
</option>
</datalist>
<input type="hidden" id='dept2' value=' 'class="form-first-name form-control" />
You can use array with push, So after finished your 5 selection all 5 values push to values array.
<script>
var values = [];
function deptchange()
{
values.push(document.getElementById("dept1").value);
}
</script>
To get the stored elements from array.
var firstElement = values[0];
datalist's option should have value attribute. and there is no need to put closing tag. it's different from select's option.
<datalist id="dept">
<?php
include 'dblayer.php';
$query = mysqli_query($mysqli,"SELECT department FROM department");
while($row=mysqli_fetch_array($query)) {
echo "<option value='". $row['department']."'>';
}
?>
</datalist>
I have a while loop that fetches all the values in the agentspec table and sets them as an option in a select field.
My values in the agentspec table are grouped by the category field and I want to use the category field as my optgroup label.
This is what I've tried. It currently outputs all the category field values followed by the all the spec values
eg.
Category: Farmer
Category: Farmer
Category: Farmer
Category: Colour
Category: Colour
Spec: Grain
Spec: Sand
Spec: Fruit
Spec: Red
Spec: Blue
I want it to output the spec values according to what group they are set in the category field.
eg.
Category: Farmer
Spec: Grain
Spec: Sand
Spec: Fruit
Category: Colour
Spec: Red
Spec: Blue
Code:
$st = DBase::singleton()
->prepare(
'select * ' .
'from `agentspec` ' .
'limit 0,30');
$option = '';
$optgroup = '';
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$id = $row->id;
$cat = $row->category;
$spec = htmlspecialchars($row->spec);
$desc = htmlspecialchars($row->desc);
$optgroup .= '<optgroup label= '.$cat.'></optgroup>';
$option .= '<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
}
}
?>
<select id="selectbox" name="" class=form-control>
<option selected="selected">Select a Specialist Area
</option>
<?php echo $optgroup;?>
<?php echo $option;?>
</select>
An option is a child element of optgroup, so you will have to do something like
this crude fiddle example:
Rewritten version for your snippet:
<?php
$st = DBase::singleton()
->prepare(
'select * ' .
'from `agentspec` ' .
'limit 0,30');
$optHtml= '';
$optgroups = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$id = $row->id;
$cat = $row->category;
$spec = htmlspecialchars($row->spec);
$desc = htmlspecialchars($row->desc);
if (!array_key_exists($cat, $optgroups)) {
$optgroups[$cat] = "";
}
$optgroups[$cat].='<option value = "agents/'.$id.'/themes">'.$spec.' , '.$desc.'</option>';
}
foreach($optgroups as $label=>$optionsHtml) {
$optHtml.= '<optgroup label="'.$label.'">'.$optionsHtml.'</optgroup>';
}
}
?>
<select id="selectbox" name="" class=form-control>
<option selected="selected">Select a Specialist Area</option>
<?php echo $optHtml; ?>
</select>