Select Group with Optgroup embedded in while loop - javascript

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>

Related

How to select an option of a slim select with jquery

I have some concatenated selects that work fine. By the way, I would like to convert those selects into slim selects but I found some difficulties in doing that.
For example, I have a select with ID level_incarico.
When I select an option of level_incarico greater than zero other selects should appear.
After that, when I change an option of a concatenated select for example in select_nazione, the option change correctly.
But when I select another time the option zero in level_incarico and the I select another time an option greater than zero in level_incarico appears another time the select select_nazione with the option already selected previously.
This is my javascript code:
$("#level_incarico").change(function(){
var option_selected = $('option:selected', this).attr('value');
document.getElementById('level_incarico_selected').value = option_selected;
if (option_selected > 0) {
$('.nazione').css('display','block');
$('.regione').css('display','none');
$('.provincie').css('display','none');
$('.comune').css('display','none');
$('.altro_nazione').css('display','none');
$("#select_regione").val(0);
$("#select_provincia").val(0);
$("#select_comune").val(0);
$("#select_nazione").val(0);
$("#altro_input_nazioni").val("");
} else {
$('.nazione').css('display','none');
$('.regione').css('display','none');
$('.provincie').css('display','none');
$('.comune').css('display','none');
$('.altro_nazione').css('display','none');
$("#select_nazione").val(0); //here
$("#select_regione").val(0);
$("#select_provincia").val(0);
$("#select_comune").val(0);
$("#altro_input_nazioni").val("");
}
});
This is how I create the selects:
new SlimSelect({
select: '#select_nazione'
})
new SlimSelect({
select: '#level_incarico'
})
In other words, the reset of the selected options $("#select_nazione").val(0); does not work correctly. It works with normal selects, but not with slim select.
Here how I fill in level_incarico:
echo "<select id='level_incarico' name='level_incarico'>";
echo "<option></option>";
echo "<option value='0' " . (($ra_level == 0 && $id > 0) ? 'selected' : '') . " >Mondiale</option>";
echo "<option value='1' " . (($ra_level == 1 && $id > 0) ? 'selected' : '') . " >Nazionale</option>";
echo "<option value='2' " . (($ra_level == 2 && $id > 0) ? 'selected' : '') . " >Regionale</option>";
echo "<option value='3' " . (($ra_level == 3 && $id > 0) ? 'selected' : '') . " >Provinciale</option>";
echo "<option value='4' " . (($ra_level == 4 && $id > 0) ? 'selected' : '') . " >Comunale</option>";
echo "</select>";
Here how I fill in select_nazione:
echo "<select id='select_nazione' name='select_nazione' required>";
echo "<option value='0'>Seleziona...</option>";
while($row = $result->fetch_assoc())
{
$nazione_id_val=intval($row['country_id']);
$nazione_nome_val=$row['country_name'];
if($ra_level > 0) {
if ($nazione_id_val == $id_nazione)
{
$selected = "selected" ;
} else {
$selected = "" ;
}
}
echo"<option value='$nazione_id_val' $selected>$nazione_nome_val</option>";
}
echo "</select>";
Can help?
Why do you have an else for the values that are all 0
Why do you have display none in both branches?
Would this help you? I got the code from the manual
const $slimNazione = new SlimSelect({
select: '#select_nazione',
onChange: (info) => {
console.log(info.value)
}
})
const $slimIncario = new SlimSelect({
select: '#level_incarico',
onChange: (info) => {
console.log(info.value)
const val = +info.value;
$('.nazione').toggle(val > 0);
$('.regione').hide();
$('.provincie').hide();
$('.comune').hide();
$('.altro_nazione').hide();
$slimNazione.set('0')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.27.0/slimselect.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.27.0/slimselect.css"/>
<select id='select_nazione' name='select_nazione'>
<option value="0">Seleziona...</option>
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
<select id='level_incarico' name='level_incarico'>
<option></option>
<option value='0'>Mondiale</option>
<option value='1'>Nazionale</option>
<option value='2'>Regionale</option>
<option value='3'>Provinciale</option>
<option value='4'>Comunale</option>
</select>
slim-select is built without jQuery...on purpose. If you have jQuery (and plan on keeping it in your stack), I would recommend using select2 instead. slim-select is a great library and has a smaller foot print due to not being dependent on jQuery. But, select2...dare I say...is better. Or, at least has more convenience features. I found select2 easier to use, but my desire to cut out jQuery led me to adopt slim-select.

How to set selected value from the database into a dropdownlist / selectbox in Laravel?

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

PHP - Dynamic Dropdown on Class value using JS

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.

Get two values from select option at once

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

This function how to use switch case

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>

Categories

Resources