Get value of Deselected option Multiselect - php

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

Related

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>

Adding 3rd Dynamic drop down menu

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

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)

localize dynamic drop down from database using jquery

This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>​
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});​
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/

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