Populating a dropdown list with jquery - javascript

I am trying to populate a drop down list using jquery and ajax.
Here's what my code looks like.
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
</script>
Here's time.php
//some code for connecting to database
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
echo"
<select name='timing' id='timing'>";
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo jason_encode($res);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo "</select>";
?>
This just puts list on time.php into a div time on my page. Is there some way I could grap individual options from the list on time .php and add them to a dropdown list on my page?
Thanks in Advance.

try:
success:function(data)
{
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.YourReturnParam + '</option>';
});
$('#yourDdlID').html(option);
}

<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
var jdata=eval('('+data+')');;
var str='';
for(var i=0;i<jdata.length;i++)
{
str.='<option>'+jdata[i]+'</option>';
}
$("#time").html(str);
}
});
});
});
time.php will return like
$res=array('a','b','v')
echo json_encode($res);

It would make it easier if the data variable that's used in the success callback is JSON or an array.
success:function(data)
{
var option = $('#time');
//Remove old options
option.empty();
//It makes it easier if you create an array to store all of the values that you want to
//populate the select tag with. I'm not sure if the data that's returned is in the form of an array or not
var newOptions = {'key1': 'value1','key2': 'value2', 'key3': 'value3'};
//Loop thru and change each option tag
$.each(newOptions, function(key, value) {
option.append($('<option></option>').attr('value', value).text(key));
});
}
And the html might look something like this, I'm guessing?
<select id="time">
<option value="val">Text</option>
<option value="val">More Text</option>
</select>

Related

Using PHP array and JS to populate values into dropdown

I'm using PHP and JS to get data from SQL table then populate the result into a dropdown list.
My code is working fine but I'm having a problem using the return output as an array for JS.
In my PHP part of the code, I'm formatting the output into JSON encode'
echo $js_array = json_encode($Unit_tenants);
// output is ["1","2","3"]
Now I want to use the return value of this output with JS to populate those values into a dropdown list with values 1,2,3
My JS code
<script>
$(document).ready(function(){
$('#ddlUnitNo').change(function(){
//Selected value
var inputValue = $(this).val();
//Ajax for calling php function
$.post('list.php', { dropdownValue: inputValue }, function(data){
//do after submission operation in DOM
var select = document.getElementById("selectNumber");
var options = data;
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
});
});
});
</script>
The problem is in var options = data because this is being recognized as a string rather than an array with multiple values. any idea how to fix this?
Javascript wont accept the php array as an array. You need to convert it to an array, or in this case a JSON object.
Try the following:
in php:
return json_encode($data);
in javascript:
var options = JSON.parse(data);
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
Try this, the PHP way
<?php $js_array = ["1","2","3"]; ?>
<select name="someName" onChange="">
<option value="" selected>Select One</option>
<?php for($k=0, $< count($js_array); $k++){ ?>
<option value="<?php echo($js_array[$k] ?>"><?php echo($js_array[$k] ?></option>
<?php } ?>
</select>

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

php How can I add additional selected items to an array

I am having problems with a list box that is set to multiple.
My setup is 3 individual list boxes, Categories(single select), Jobs(single select), and Tasks(multiple select)
When a users selects one item in Categories an ajax request populates the Jobs list box.
when a user selects one item from Jobs an ajax request populates the tasks box with one or more pre-selected items, plus the un-selected items.
All this works well my problem araises when I try to select additional items in tasks the pre selected items clear. I need the pre selected items to remain selected and be able to select additional items. I am using a function to select the additional item and refresh the tasks list box so that I do not have to press ctrl when selecting an item.
Here is my html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<?php
session_start();
include('dbcon/dbconnect.php');
$con=mysqli_connect($host,$user,$password,$db);
?>
<script>
function getSelectedItems(){
var items = "";
var frm = document.forms[0].s1;
var len = frm.length;
for(i=0;i<len;i++){
if(frm[i].selected){
items += frm[i].value + "~";
}
}
alert(items);
}
$(document).ready(function(){
$("select#cat").change(function(){
var cat_id = $("select#cat option:selected").attr('value');
$("#job").html( "" );
if (cat_id.length > 0 ) {
parent.top.$("#jobbtn").val("Change Category");
$.ajax({
type: "POST",
url: "fetch_jobs.php",
data: "cat_id="+cat_id,
cache: false,
beforeSend: function () {
$('#job').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#job").html( html );
}
});
}
});
$("select#job").change(function(){
var job_id = $("select#job option:selected").attr('value');
invid = 0;
$("#task").html( "" );
if (job_id.length > 0 ) {
$.ajax({
type: "GET",
url: "1a.php",
data: "job_id="+job_id+"&invid="+invid,
cache: false,
beforeSend: function () {
},
success: function(html) {
$("#task").html( html );
var selected = $("#task").val();
}
});
}
});
});
function getnotes(){
}
</script>
</head>
<body>
<form id="form1" >
<select id="cat" size="12" style='font-style:arial;font-size:14px;'>
<?php
$result = mysqli_query($con, "SELECT CatID, Catagory FROM catagory ORDER BY Catagory");
while($row = mysqli_fetch_array($result))
{
echo "<option value=\"".$row['CatID']."\">".$row['Catagory']."</option>\n ";
}
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:0px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='jobl' style='position:fixed;left:180px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933 ;width:340px;height:20px;'>Jobs</span></div>";
echo "<select name='job' id='job' size='12' style='position:fixed;left:180px;top:23px;width:340px;font-size:14px;font-family:Arial;' onchange='' >";
echo "<option value='' ></option>";
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='taskl' style='position:fixed;left:535px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933;width:335px;height:20px;'>Tasks</span></div>";
echo "<select name='task' id='task' size='12' style='position:fixed;left:535px;top:23px;width:335px;font-size:14px;font-family:Arial;' onchange='getnotes()' multiple>";
echo "<option value='' ></option>";
echo "</select>";
echo "<input type='submit' id='taskb' name='taskb' style='position:fixed;top:330px;left:700px;width:150px;height:60px;font-size: 22px;font-weight: bold;white-space:normal;background:Lime;' value= 'Add Task->' onclick='shofinal();'></form></div>";
echo "</form>";
?>
<script>
(function() {
var selected = {};
$('select#task').click(function(e) {
var $this = $(this),
options = this.options,
option,
value,
n;
// Find out what option was just added
value = $this.val();
// Re-apply the selections
for (n = 0; n < options.length; ++n) {
option = options[n];
if (option.value == value) {
// The one being updated
selected[value] = !selected[value];
}
// One of the others
option.selected = !!selected[option.value];
}
});
})();
</script>
</body>
</html>
I believe my problem is in the script at the end of the html but I am unsure of what to change to fix this.
I have finally gotten this worked out thought I would post what fixed it for others to see/use
I added this jquery to the $(document).ready(function()
and now pre selected items stay selected and newly selected items are selected or if I click an item that is already selected it becomes unselected. I am pretty sure I understand what is happening here though I can not put it into words. But it works and I guess that is whats important.
I also removed the script from the end of the original html and everything is good so far.
Works in FF
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}

Select2 Custom Tags, Transform Value on Select

I would like a dropdown of text and then when one is selected I would like to load the full value as the tag and have it behave as normal.
I'm capturing the values selected then clearing the list and appending them as text into the .select2-choices div. It appears to work as it should but I've lost the ability to clear the manually appended tags.
Markup:
<div id="select2-container">
<select multiple class="select2" id="select2">
<optgroup label="GroupName">
<option value="John Smith - GroupName (ID:12345678)">John Smith</option>
</optgroup>
</select>
</div>
Script:
$('#select2').select2({
}).on('change', function (e) {
values = $(this).val();
console.log(values);
$('#select2-container .select2-choices').empty();
for (var i = 0; i < values.length; i++) {
console.log(values[i]);
$('#select2-container .select2-choices').append('<li class="select2-search-choice"><div>' + values[i] + '</div></li>');
}
});
I'm going to look into the formatSelection function but any help is greatly appreciated.
You've probably solved this by now, but you are correct that you want to use formatSelection.
Be default, the selected object's text property is used, but you want the id property instead. The id property is the <option> element's value.
$('#select2').select2({
formatSelection: function(object) {
return object.id;
}
});
jsfiddle
This is a solution in my project:
In edit.php file:
solution 1 (cate id is single number):
<?php
$cate_row = $db->fetchRow("SELECT cate_id, cate_name FROM categories WHERE cate_id=".$editdata[cate_id]." AND cate_status='Active'");
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
solution 2 (cate id is array: 12,4,5,6 or ,12,4,5,6,):
<?php
$cate_q = $db->query("SELECT cate_id, cate_name FROM categories WHERE cate_status='Active' ORDER BY cate_name ASC");
// array: ,12,4,5,6,
$editcate_array = explode(",", substr($editdata[cate_id], 1, $editdata[cate_id] - 1));
// or array 12,4,5,6
// $editcate_array = explode(",", $editdata[cate_id]);
while($cate_row = $db->fetch_array($cate_q)){
if(in_array($row['cate_id'], $editcate_array)) {
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
}
}
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
In JS global.js:
function AjaxCombo(elm, url, multiple) {
$(document).ready(function() {
$(elm).select2({
multiple: multiple,
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return {results: data};
}
},
// Add new category if no exist
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
$(elm).select2("data", JSON.parse($(elm).val()));
});
}
Default if form edit have cate data select2 init "id - Name category".
in file getCategories.php : from select you get $q = $input->gc['q'] and mysql is cate_name LIKE '%" . $q . "%';
while($row = $db->fetch_array($result)){
$dataArray[] = array("id"=>$row['cate_id'], "text"=>$row['cate_id']." - ".$row['cate_name']);
}
header('Content-Type: application/json');
echo json_encode($answer);
when get value form select2 you can try:
foreach ($_GET['select2'] as $value) {
echo $value;
}
done!

Pull dropdown Options from a DB based on selection in another dropdown

I have two dropdown lists as a part of a form I'm creating, both of which have options that are being pulled from a mysql database. I would like the options in the second dropdown to change based on the selection in the first dropdown. I know how to do this using Javascript when the second list is static, but I would like both dropdowns to dynamically pull from the database. Below is the HTML and Javascript I'm currently using. Any ideas would be great.
HTML:
<form>
<label for="org_name">Organization Name:</label>
<select id="org_name" name="org_name" onchange="configureDropDownLists(this,'submitter_name')">
<option value="empty"> </option>
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$query = "SELECT * FROM Table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<option value='" . $row['org_name'] . "'>" . $row['org_name'] . "</option>";
}
mysql_close();
?>
</select>
<label for="submitter_name">Request Submitted By:</label>
<select id="submitter_name" name="submitter_name">
<option value="empty"> </option>
</select>
<input type="Submit" value="Submit">
</form>
Javascript:
function configureDropDownLists(org_name,submitter_name) {
var org = new Array('Submitter 1', 'Submitter 2');
switch (org_name.value) {
case 'org':
document.getElementById(submitter_name).options.length = 1;
for (i = 0; i < org.length; i++) {
createOption(document.getElementById(submitter_name), org[i], org[i]);
}
break;
default:
document.getElementById(submitter_name).options.length = 1;
break;
}
createOption(document.getElementById(submitter_name), 'Other', 'Other');
if (org_name.value === 'empty') {
document.getElementById(submitter_name).options.length = 1;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
As suggested, AJAX was the answer. For anyone curious who comes across this, below is the solution I came up with. I left the HTML unchanged other than removing onchange="configureDropDownLists(this,'submitter_name')" from the first dropdown. Instead of the above Javascript, I used the below AJAX and PHP. Works really nicely.
JQuery:
$(document).ready(function() {
$("#org_name").on("change", function() {
var orgName = document.getElementById("org_name").value;
$.post('admin_list.php', { org: orgName }, function(result) {
$('#submitter_name').html(result);
}
);
});
});
and the referenced PHP page:
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$org_name = $_REQUEST['org'];
$query = mysql_query("SELECT * FROM Table WHERE user = '$org_name'");
while($row = mysql_fetch_array($query)){
echo "<option>" . $row['admin_first_name'] . " " . $row['admin_last_name'] . "</option>";
}
mysql_close();
?>
Sounds like you need some AJAX to pull your data from the database, format on the server side (JSON will likely be easiest to work with), then use a callback function in Javascript to populate the second drop down based on the JSON data received.

Categories

Resources