Dropdown list where options populate a second list js/php? - php

I have a 2 dropdown lists side by side. When user selects from the first list, i need the second list's options to be displayed.
The sub-options will be retrieved from a database. I have a page that will return the necessary html given the specific parent. I just need the first list's selection to trigger an update of list #2.
Whats the best way of accomplishing this?
<select id="parent" name="list1">
<option value="1">Parent 1</option>
<option value="2">Parent 2</option>
<option value="3">Parent 3</option>
<option value="4">Parent 4</option>
</select>
<select id="child" name="list2">
</select>
caveat: cant use a form, cause the selection's are part of another form.

The normal way to do this is to do an AJAX request after the first dropdown is selected to retrieve the contents of the second.
Exactly how you do that will depend on the frameworks/libraries you're using, but here's an example of a jQuery plugin designed for it:
jQuery cascade plugin
There's also a number of related questions on SO that may help:
https://stackoverflow.com/search?q=cascading+dropdown

Use the event onchange of the select to call an ajax function to retrieve the new data

A dead simple way is to set up your script to output the entire markup of the generated select list, and inject that into a wrapper element, e.g.:
<div id="wrapper">
<select id="child" name="list2">
</select>
</div>
$("#parent').change(function() {
$('#wrapper').load('getSelect.php','selection=' + $(this).val());
return false; // may or may not be needed
});

Related

Geodan's Dual List Box: populating 'selected' box with different JSON file (PHP).

The goal is a subscription page where users can select properties to subscribe to. This works.
What I have: I'm using Geodan's plugin for being able to select items from the left list box (unselected) and moving them over to the right list box (selected). The left list box is populated via JSON, like so:
<div class="form-group">
<label for="properties">Properties</label>
<div id="dual-list-box" class="form-group row">
<select class="filter" name="dropdown[]" multiple="multiple" data title="Properties"
data-source="properties.json" data-value="index" data-text="name"></select>
</div>
</div>
Then you call this like so:
$(document).ready(function() {
$('.filter').DualListBox();
});
This works just fine. You can move properties from properties.json over to the right list box.
What I want to achieve:
Even though this initial subscription page works this fine, say a user wants to edit their subscription. Maybe they initially subscribed to ten properties, but now they want to add ten more. What you would want is:
-a separate page with the left list box being populated with properties.json
-the right list box being populated with a separate JSON file generated via PHP (getting the JSON file is easy): but I'm not sure if this plugin even allows to populate the right list box from an external source.
I emailed Geodan roughly a week ago but have not heard back.
Any help on what I'm trying to achieve is appreciated. I am also open to using other plugins, if that would be an easier route.
You don't need to generate separate JSON for the left and right listbox. You just need to add the "selected" attribute to the options you want on the right.
Example:
<select id="ItemIds" name="ItemIds" multiple="multiple" data-title="Items" data-horizontal="false" data-json="false">
<option value="1">Item 1</option>
<option value="1" selected="selected">Item 2</option>
<option value="3">Item 2</option>
<option value="4" selected="selected">Item 4</option>
</select>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#ItemIds').DualListBox();
});
</script>
Reference https://github.com/Geodan/DualListBox/issues/5

multiple select dropdown - need a hidden selected value or always selected value

I have a multiple select dropdown such as so. I need to ALWAYS include a specific value in 'settings[users][]' when it is passed regardless if other values are selected in the dropdown or not.
I have found some jquery solutions... is there any other way to add a specific value to this array? The actual value does not need to be shown in the selection area it just needs to always be included in the array when posted.
Basically what is happening is a user is selected to be edited which bring up different settings which can be changed. I am using this select box to allow them to set these new settings to other users if they wish. So, the original user value they are editing must always be present in 'settings[users][]' when it passed to my php script for processing.
<select multiple="multiple" name="settings[users][]" size="8">
<option value="" selected="selected">no additional users...</option>
<option value="1">User 1</option>
<option value="2">User 2</option>
<option value="3">User 3</option>
<option value="4">User 4</option>
</select>
EDIT :
I didn't really get the responses I was looking for... here is what I am doing currently.
added hidden field to the form of the always selected user :
<input type="hidden" name="user_id" value="someuserID"/>
in php then :
// push always selected user id to the posted array
array_push($_POST['settings']['users'], $_POST['user_id']);
// filter out any empty value such as if 'no additional users...' was left selected
$userArray = array_filter($userArray);
$userArray now equals all users I need to edit/change in my php
The comments here are trying to (gently) point out the fact that what you want to do is almost certainly unnecessary, and it's needlessly complicating the code -- do you really want to complicate the HTML (the bit that any user can see) just to simplify the PHP?
Having said that I can imagine a possible case where you might need to do this, and I'll get to that. But let me cover the other cases first.
First, if the fixed value is permanently fixed over the entire web site / application then just hardcode it in PHP. As Amir Bawab says in the comments:
$_POST['settings'][] = "someuserID"; // or array_push if you prefer
// Carry on as normal here ...
Second, if the value changes depending on the site context and so is only known to the HTML then your solution in the edit is absolutely the right way to do it. It's clean, it's obvious what's going on in the HTML and PHP, it'll be easy to debug and support later.
But, perhaps you don't have access to the PHP page and absolutely need to post the right structure. As you say you can do this in jQuery/Javascript by intercepting the form submit and inserting the extra hidden value marked as selected.
However, if you're determined to do it as pure HTML (maybe you don't have scripting) then you can do this:
<select multiple="multiple" name="settings[users][]" size="8">
<option value="" selected="selected">no additional users...</option>
<option value="1">User 1</option>
<option value="2">User 2</option>
<option value="3">User 3</option>
<option value="4">User 4</option>
</select>
<select style='display:none' multiple="multiple" name="settings[users][]">
<option value="someusedID" selected="selected"></option>
</select>
If I print_r($_POST) in PHP I get (I selected user 2):
Array
(
[settings] => Array
(
[users] => Array
(
[0] => 4
[1] => someusedID
)
)
)
Which is what you want, I think.
Note, I tried this on Chrome via a local server (XAMPP) I can't swear that all browsers and setups will handle this the same way. That's why the hidden field approach is a much better idea.

How to populate dropdown list from mysql db and based on selection populate another dropdown list in php form?

I have situation where i have column in mysql table from which i populate dropdown list for criteria for query for second dropdown list from another table. How coud i do that using php and selection of second dropdown list pass to another input form? I have same formBarkod column in both tables which is connection between tables data.
This sounds like a job for javascript. You could populate each of the dropdowns with php and mysql, but you'd need javascript to have the selection on the first dropdown affect which of the next dropdowns is visible. The PHP and MySQL would look like this:
<?
//Assuming $dbh is a proper mysqli object...
$options = $dbh->query("SELECT * FROM options");
echo '<select id="firstDropdown">';
while($o = $options->fetch_object()) {
echo '<option value="'.$o->id.'">'.$o->name.'</option>';
}
?>
Repeat that process for each dropdown.
Then you have to write some javascript to work on the change. I don't know enough "pure" javascript to do this, but I can show you what it'd look like in jQuery. Assuming your html looks like this:
<select id="firstDropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="dropdown1" class="dropdown">
...
</select>
<select id="dropdown2" class="dropdown">
...
</select>
<select id="dropdown3" class="dropdown">
...
</select>
Then the jQuery would look like this (all wrapped in a document.ready() of course)
$(".dropdown").hide();
$("#firstDropdown").on("change",function(){
$(".dropdown").hide();
var value = $("#firstDropdown").val();
$("#dropdown"+value).show();
});
The basic flow is that you hide all of the secondary dropdowns. Then, whenever the value in the first dropdown changes, you rehide the secondary dropdowns, and show only the desired dropdown. You can do a lot more with this by actually creating the dom elements on the fly or by using an ajax call to get the new dropdowns, but this covers the basic concept.
EDIT: Here's a working example on jsfiddle.net

Update form on same page using Ajax, PHP, MySql

Need help on this problem.
I have a form being displayed on let's say index.php containing many different fields i.e. drop-down, textfields,...
On the same page, I have a drop-down list containing values coming from my database.
I need to fill in the form based on the value selected from the drop-down list.
Is there a solution for this problem using ajax or even any other way of doing it?
Thanks in advance?
you have to use javascript/ajax. You can use jQuery for this.
You need something like this:
<script type='text/javascript'>
function changeOptions(value,objId){
respond = sendRequestToAPHPScript(); // respond is a string that your php script returns; should contain html for the select box.
${objId}.innerHTML = respond;
}
</script>
<select id="mySelect" onchange="changeOptions(this.value,'mySelect2');">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select id="mySelect2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
When you change the dropdown value of the first dropdown a javascript function (changeOptions) is called. The function sends a request to your php script, which outputs html with data from your database. The function then fills the other select box with returned html from the request.
You could listen for changes in the selected dropdown field and make an ajax request to a script that queries the database and returns the desired information in JSON. You'd then have to apply the values to the specified input fields.
Update:
You'll have to figure out the ajax part yourself, but this should get you started. The sample is built using the jquery library.
http://jsfiddle.net/k4emic/4qAE2/2/

How to keep the correct selection in form with dynamically changing options?

I have the following problem. I’ve made a form which change the form elements dynamically depending on the option it’s selected. Here is short example:
<select name="vehicle" id="vehicle" onchange="$('#div').load('data.php?vehicle='+this.value);">
<option value="1"> motorcycle</option>
<option value="2">buss</option>
<option value="3"> truck </option>
<option value="4">. . .</option>
</select>
<div id="div">
<select name="moto_type" id="moto_type">
<option value="1">Ducati</option>
<option value="2">Yamaha</option>
<option value="3">Kawasaki</option>
<option value="4">. . . </option>
</select>
</div>
When buss is selected from the dropdown menu the content of #div is substituted with options available for busses, such as:
<select name="bus_type" id="bus_type">
<option value="1">A-type</option>
<option value="2">B-type</option>
<option value="3">C-type</option>
<option value="4">. . .</option>
</select>
<select name="bus_seats" id="bus_seats">
<option value="1">10</option>
<option value="2">20</option>
<option value="3">50</option>
<option value="4">. . .</option>
</select>
Identically all other options change depending on what is selected in that first dropdown menu. After the form is submitted the results are processed and table of results shown. However if the user hits the edit button to go back and edit their choice, the choice in the first dropdown menu is saved (let’s say bus) but the dropdown menus for option bus #2 (buss_type and bus_seats) in #div are replaced with the options for motorcycle #1 (moto_type) which is not correct. I understand why that is happening, what I can’t find out is how to show the user their correct form selection. How to show the correct sub options for each value in the main dropdown menu when the user comes back to the form to edit it?
Any help is appreciated!
Additional question:
How do you keep the correct selections in the secondary drop down menus, so they don’t switch back to the default value=”1”?
Don't use inline event handlers, they can only cause you headaches... They are not flexible and don't let you separate your semantic markup and behaviour.
Instead, do something like this (you can put this in a script tag just before body, preferably in a separate file with all your other JS):
$(document).ready(function () {
$('#vehicle').change(function () {
$('#div').load('data.php?vehicle='+$(this).val());
}).change();
});
Notice that you attach the change event handler, and immediately after that you also call it. That ensures that it will load on page load and onchange either.
Also check when the form is initially loaded, not just onchange of the drop down.
i have something similar in asp with dynamically shown divs. I have a function that does the work and I call the function both for the onchange AND when the form initially loads.

Categories