Adding 3rd Dynamic drop down menu - php

I already have this code working for 2 selection menus, now I am trying to add a third but the third is just showing all of the sub-sub categories, rather than being based on the previous selections..
Here is the menu code, I'll just show 1 selection example so it's easier to read.
<select name="category" id="category">
<option value="Sport">Sport</option>
</select>
<select name="sub_category" id="sub_category">
<option value="Golf" class="Sport">Golf</option>
</select>
<select name="subsub_category" id="subsub_category">
<option value="Mens" class="Golf">Mens</option>
<option value="Ladies" class="Golf">Ladies</option>
</select>
JS CODE
<script src="js/menu.js"></script>
<script type="text/javascript">
window.onload = function() {
dynamicSelect("category", "sub_category", "subsub_category");
}
</script>
MENU.JS
function dynamicSelect(id1, id2, id3) {
// Browser and feature tests to see if there is enough W3C DOM support
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac = (agt.indexOf("mac") != -1);
if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
// Obtain references to both select boxes
var sel1 = document.getElementById(id1);
var sel2 = document.getElementById(id2);
var sel3 = document.getElementById(id3);
// Clone the dynamic select box
var clone = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions = clone.getElementsByTagName("option");
// Onload init: call a generic function to display the related options in the dynamic select box
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
sel1.onchange = function() {
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
};
}
}
function refreshDynamicSelectOptions(sel1, sel2, sel3 clonedOptions) {
// Delete all options of the dynamic select box
while (sel2.options.length) {
sel2.remove(0);
}
// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
var pattern1 = /( |^)(select)( |$)/;
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
var pattern3 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
// Iterate through all cloned options
for (var i = 0; i < clonedOptions.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2) || clonedOptions[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions[i].cloneNode(true));
sel3.appendChild(clonedOptions[i].cloneNode(true));
}
}
}

Edit: Had to change a lot to get it working, but it is working now, here: http://jsfiddle.net/kvAWf/11/
Here's the resulting Javascript:
var sel1 = document.getElementById('category');
var sel2 = document.getElementById('sub_category');
var sel3 = document.getElementById('subsub_category');
// Clone the dynamic select box
var clone2 = sel2.cloneNode(true);
var clone3 = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions2 = clone2.getElementsByTagName("option");
var clonedOptions3 = clone3.getElementsByTagName("option");
sel1.onchange = function(){
refreshSelect2();
}
sel2.onchange = function(){
refreshSelect3();
}
function refreshSelect2() {
while (sel2.options.length) {
sel2.remove(0);
}
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions2.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions2[i].className.match(pattern2)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions2[i].cloneNode(true));
}
}
refreshSelect3();
}
function refreshSelect3() {
while (sel3.options.length) {
sel3.remove(0);
}
var pattern3 = new RegExp("( |^)(" + sel2.options[sel2.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions3.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions3[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel3.appendChild(clonedOptions3[i].cloneNode(true));
}
}
}

Related

Html select data to PHP

How to get the html Select value in php?
i have made this Select in html
<select id="year" onchange="filterYear();">
</select>
Function to fill in the Select:
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for (var i=5; i<n; i++) {
select.options[select.options.length] = new Option(i+1, i);
}
}
but i need to read the current selected item from the select.
i tried this (javascript):
function filterYear() {
var e = document.getElementById('year');
var value = e.value;
var text = e.options[e.selectedIndex].text;
alert(text);
}
php:
$text = $_GET['text'];
echo $text;
but this did not work
any ideas on how to fix this
i hope someone can push me in the right direction
Without submitting a form and thus reloading the page you can easily send an ajax request that can be processed by the PHP server script. The response from the server is then used in the callback to, usually, perform further DOM manipulation or whatever.
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for( var i = 5; i < n; i++ ) {
select.appendChild( new Option( i + 1, i ) );
}
}
// build the menu
selectOne();
// bind event listener externally
document.getElementById('year').addEventListener('change',e=>{
// a callback to process response from PHP script
let callback=(r)=>{
alert(r)
};
// send a GET ajax request and process response
fetch( 'path/to/php/script.php?text='+e.target.value )
.then(r=>r.text())
.then(callback)
.catch(alert)
})
<select id="year" name='year'>
</select>

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

Populating a third dropdown with a query result

I have three dropdowns. Based on the option selected in first dropdown i am populating the second dropdown using javascript.
First dropdown
<select id="continent" onchange="secondMenu(this,'country')" >
<option value="1">Asia</option>
<option value="2">Europe</option
</select>
Second dropdown
<select id="country" >
</select>
Third dropdown
<select id="population" >
</select>
My script
<script>
function secondMenu(ddl1,ddl2){
var as=new Array('Japan','China');
var eu=new Array('Germany','France');
switch (ddl1.value) {
case 1:
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < as.length; i++) {
createOption(document.getElementById(ddl2), as[i], as[i]);
}
break;
case 2:
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < eu.length; i++) {
createOption(document.getElementById(ddl2), eu[i], eu[i]);
}
break;
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
Now based on the option selected in second dropdown i want to run a mysql query and populate the third dropdown. Any help on how to go about populating the third dropdown.
Use AJAX to send a request to your server and run mysql query. Assuming, you are not using JQuery, pure AJAX looks something like this:
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
//populating your select
}
}
xmlhttp.open("GET", "yourmethodpath", true);
xmlhttp.send();
}
Use Ajax, I do something very similar in one of my projects, so heres an example:
$('#product_series_text', $('#product_form')).change(function() {
var $series = $(this).val();
// Ajax request to get an updated list of product models
$.getJSON(
"<?php echo url::site('product/get_model_like_series'); ?>",
{ series: $series },
function(data) {
$("#product_model",
$('#product_form')).form_utils('replaceOptions', data);
});
});
Theres a lot of jQuery there, but the idea is to have an eventlistener for a change in one dropdown, then fire off an Ajax query (which polls the database and sends back a Json list of results), which then create a dropdown list for us (just the options are changed as the dropdown list already exists)

Get value of Deselected option Multiselect

I have a form that has a 2 select boxes for dependent lists.
I'm loading a second list based on the value selected in the first list, which is multiselect.
<select id="list1" multiple='multiple'>
<option value="a">a value</option>
<option value="b">b value</option>
<option value="c">c value</option>
</select>
<select id="list2">
</select>
For each option added to list2, I'm also adding a class with value of list1 corresponding to the list2 value.
For loading the elements for the selected option, I use the code:
$('#list1').on('change', function(){
var list1vals = $('#list1').val().split(',');
var newval = '';
for(x in list1vals)
{
// Checking for selected value of list1 which doesn't have
// corresponding values in list2.
if($('.'+list1vals[x]).length == 0)
{
newval = list1vals[x];
}
}
$.ajax({
type : "GET",
url : "/xyz.php?action=getlist2&list1="+newval,
success : function(response)
{
if($.trim(response) != '')
{
$('#list2').append(response);
}
}
});
});
xyz.php
$action=$_GET['action'];
$listval1=$_GET['list1'];
switch($action)
{
/////////////////
case 'getlist2':
$list2 = fetchlist2($list1val);
foreach($list2 as $listobj)
{
$optionlist = '<option class="'.$list1val.'" value="'.$listobj['id'].'">'.$listobj['value'].'</option>';
}
echo $optionlist;
break;
////////////////
}
Is there any way in which I can remove the element unselected in list1 from list2?
i.e when an option is unselected, I want to remove all elements in list2 having class value of the unselected element.
Note : The operation for fetching the list in fetchlist2 is expensive and hence I want to handle removal of element in javascript.
you could try this if you just want the unselected options from list1 to be removed from list2:
$('#list1').change(function(){
var lists = $('#list1').val();
var str = '';
if (lists != null){
for(var i=0;i<lists.length;i++){
str += '<option value="'+lists[i]+'">' + $('#list1 option[value="'+ lists[i]+'"]').text() + '</option>';
}
}
$('#list2').html(str);
});
or if you just want to remove an option element with a class that is the value of the unselected element from list1:
$('#list1 option:not(:selected)').click(function(){
$('#list2 option[class="'+ $(this).val() +'"]').remove();
})
Im sorry if I was not able to express my problem properly.
These are 2 different lists, with the value of first list determining what was to be loaded in the second list, similar to selecting category and loading subcategory based on selected category.
I sort of figured out a way to do it. This is how I did what I wanted:
var list1vals = ($('#list1').val()+'').split(',');
var newval = '';
for(x in list1vals)
{
/// Checking list2 elements to see
/// which list1 selected element is not present
if($('.'+list1vals[x]).length == 0)
{
newval = list1vals[x];
}
}
if(newval == '')
{
/// Some Element removed, checking which
/// options remain selected
var options1,list2options = [];
$('#list1 option:selected').each(function(){
options1 = $('#list2 option[class="'+ $(this).val() +'"]');
list2options.push(options1);
});
$('#list2').html('');
$('#list2').append(list2options);
}
else
{
$.ajax({
type:"GET",
url:"/xyz.php?action=getlist2&list1="+newval,
success:function(response)
{
selectbox = $('#list2');
var list2 = $.parseJSON(response);
/// Adding options returned for newval to list2
/// with class set as newval
for(x in list2)
{
var option = $('<option></option>');
$(option).attr('value',list2[x].value);
$(option).html(list2[x].value);
$(option).addClass(newval);
$(selectbox).append(option);
}
}
});
}

Dynamically created form elements value not getting in $_POST in php

I have created some dynamic text boxes and values according to the no. of cart items selected by a user. The no. of cart items are stored in a cookie and I am trying to do the following:
1) Get the no. of cart items from the cookie named cartcounter
2) Create 'cartcounter' no of text boxes with name itemkey_skey where itemkey is the hash key of each items in user cart.
3) Submit the form
4) Get the keys of the selected items in php
Now I can create cartcounter, the number of text boxes with different values.
But the problem is that I can get only the first text box value in $_POST in PHP. I would like to get all the values of the dynamically created form elements.
Code:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
$("#frm").submit();
}
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​
I have solved it. The problem was that I was calling the submit function inside the loop. I have solved it by doing:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
}
$("#frm").submit();
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​

Categories