Im trying to create a select which is dynamic, for example if there is 3 item in the database gift, then it will create 3 select with value from the database lecturer. This is the javascript to create the select when the user click the button add.
Now after the user have create 3 select and submit it, if the user wish to edit back the data, how can I do it ?
function addField(area,field,limit)
{
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("select");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
if(document.createElement)
{
var li = document.createElement("li");
var input = document.createElement("select");
var opt = document.createElement("option")
input.id = field;
input.name = field;
opt.value = "NULL";
opt.textContent = "NO LECTURER";
li.id = "li"+last_item;
input.appendChild(opt);
li.appendChild(input)
$(document).ready(function()
{
$.ajax
({
type:"post",
url: "event/data.php",
success: function(data)
{
console.log(data);
$(input).append(data);
}
});
});
field_area.appendChild(li);
}
}
Here example of what I have create,
http://i.imgur.com/je1MchL.png
Here how it works
http://i.imgur.com/c4ICTWt.png
So basically in the database have 5 data, so what im trying to do is in the next page it will automatic create the exact 5 select. How can I do this?
Thanks
Create a function (useful for reuse)
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
and call it:
// $options : return array from DB
$curr = 'some_key';
$select_name = 'my_select';
echo create_select($select_name,$options,$curr);
A complete working example:
<?php
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('effone_db');
$query = mysql_query("SELECT * FROM settings");
while ($row = mysql_fetch_array($query)) {
$options[$row['option']] = $row['option_value'];
}
echo create_select('settings',$options,'100');
?>
Let's assume that $options holds the resulting query.
So what you must do is loop thru the items and echo them inside a <select> tag.
like:
<html>
<body>
<select name='nameUrSelectHere'>
<?php
foreach($options as $option){
echo "<option value='" . $option['column_one'] . "'>" . $option['column_two'] . "</option>" ;
}
?>
</select>
</body>
</html>
Related
how to fill dropdown values on selection of multiple dropdown.for example i have following Dropdown list.
On select of second dropdown i wants to fill Third Dropdown With Single selection How can i do. ?
My current code for this is as follow.
//CALL FOR SECOND DROPDOWN
$(document).ready(function(){
$('#select4').on('change',function(){
var subcatgoryId = $(this).val();
console.log(subcatgoryId);
if(subcatgoryId){
$.ajax({
type:'POST',
url:'ajax_load_specification.php',
data:{subcatgoryId: subcatgoryId},
success:function(html){
alert(html);
//$('#select5').html(html);
//$('#loading1').css("display","none")
},
error: function (jqXHR, exception) {
alert("Got Some Errore");
}
});
}else{
$('#select5').html('<option value="">Select Category first</option>');
}
});
});
and php code is as follow
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = explode(',', $_POST["subcatgoryId"]);
print_r($_POST["subcatgoryId"]);
foreach ($subcategory as $key => $value)
{
echo $key;
echo "<br>";
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$item." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}
Just Use For Loop And it starts working
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = $_POST["subcatgoryId"];
$len=count($subcategory);
for ($i=0; $i < $len; $i++) {
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$subcategory[$i]." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}
I am using more than one dropdown in may page the first being:-
function createCFAList()
{
$ajax = false;
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['cl']))
{
$SelectedCFAName = $_GET['cl'];
$ajax = true;
}
$sql = "SELECT DISTINCT `cfalist`.`CFA`
FROM `amwplist`
INNER JOIN `cfalist` ON `cfalist`.`CFA_ID` = `amwplist`.`CFA_ID`";
$result = mysql_query($sql);
$CFAlist = "<select id='cfa5' name='cfa5'>";
while ($row = mysql_fetch_array($result)) {
$CFAlist = $CFAlist . "<option value='" . $row['CFA'] ."'>" . $row['CFA'] ."</option>";
}
$CFAlist = $CFAlist . "</select>";
return ($CFAlist);
}
The Second list being:-
function createStatusList()
{
$ajax = false;
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['ss']))
{
$SelectedStatus = $_GET['ss'];
$ajax = true;
}
$sql = "SELECT `Status_ID`,
`Status_Type`
FROM `workstatuslist` ";
$result = mysql_query($sql);
$Statuslist = "<select id='status4' name='status4'>";
while ($row = mysql_fetch_array($result)) {
if($row['Status_Type'] == "BOO in Progress")
{
$Statuslist = $Statuslist . "<option selected='" . $row['Status_Type'] ."'>" . $row['Status_Type'] ."</option>";
}
else
{
$Statuslist = $Statuslist . "<option value='" . $row['Status_Type'] ."'>" . $row['Status_Type'] ."</option>";
}
}
$Statuslist = $Statuslist . "</select>";
return ($Statuslist);
}
These two functions are placed in function.php and are called from AMWP.php to display the Dropdown. The selected options are stored in variables
global $SelectedStatus and global $SelectedCFAName
using the following script in AMWP.php:-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -->
<script>
$('#status4').change(function()
{
var status4 = $('#status4').val();
var req = $.get('functions.php', {ss: status4, action: 'ajax'});
});
$('#cfa5').change(function()
{
var cfa5 = $('#cfa5').val();
var req = $.get('functions.php', {cl: cfa5, action: 'ajax'});
});
</script>
How may I store the Selected Option onChange to the variables declared global $SelectedStatus and global $SelectedCFAName
and then use them to create SQL Statement like whenever the Selected option is changed by the user
$sql="SELECT * FROM abc WHERE status LIKE $SelectedStatus AND cfa LIKE $SelectedCFAName";
I have found the solution at this URL
SourceCodester Dot Com
Found One more good sample source at this link
PHP Jquery Dropdown sample. Good One
$sql = 'SELECT a.guest_id, g.fname, g.lname, g.ph1, g.email, g.arrpickup, g.arrdropoff, a.approxtime, a.vehicle_id1, a.vehicle_id2, a.vehicle_id3,FROM arrivals a INNER JOIN guest g ON a.guest_id = g.guest_id WHERE g.guest_id = 18';
with this I am getting data from the database using inner join.
$html = null;
$html .= '<select>
<option value="-1"> ----Select Vehicle---- </option>';
$sql1 = 'SELECT * FROM vehicle ORDER BY vehicle_id ASC';
foreach ($pdo->query($sql1) as $row1) {
$html .= '<option value="">'. $row1['model'] . ' - ' . $row1['licplate'] . ' </option>';
}
$html .= '</select>';
this is drop down mechanism for getting data from table
its showing using
echo '<tr><td>Vegicle 1</td><td>'.$html.'</td></tr>';
now I want to store selected value to table so where to put insert query ? all connection stuff again ?
$upd_row['your value'];
change your get table value in inert a database.
and follow this code and some changes your requerment.
i hope help in your code.
$idproduct= "select * from `country_master`";
$str = mysql_query($idproduct);
$select="";
$issel = '';
if(mysql_num_rows($str)>0)
{
while($viewrow=mysql_fetch_array($str))
{
if($upd_row['your value'] == $viewrow['id'])
{
$select = "selected";
$issel = 'yes';
}else
$select ="";
$opts .= "<option value='".$viewrow['id']."'".$select." >".$viewrow['country_name']."</option>";
}
}
if($issel == '')
$opts = '<option value="" selected>--Select--</option>'.$opts;
else
$opts = '<option value="" >--Select--</option>'.$opts;
echo $opts;
?>
I have created a main drop down list and with jquery I can choose the number of drop down menus to display. Done very simply by a for loop. The main dropdown list to choose how many drop downs to display is statically populated and I am trying to dynamically populate the drop downs being displayed with data in mysql database. In the php side I am using a while loop to populate each select box. I am not getting any results being displayed. SITE
<script type="text/javascript">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'"><option value="">--- Select ---</option>"'
<?php
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$course_query = "SELECT course_id, course_name FROM course ";
if($result = mysqli_query($mysqli, $course_query)) {
while ($idresult = mysqli_fetch_row($result))
{
$course_id = $idresult[0];
$course_name = $idresult[1];
echo'<option value="' . $course_id . '">' . $course_name . '</option>';
}
}
?>
'"';
content += '</select><br /><div><br />';
}
$('#course_catalog').html(content);
}
});
</script>
You need to echo a javascript line to start with, instead of echoing directly...
echo 'content += \'<option value="' . $course_id . '">' . $course_name . '</option>\';';
I’m trying to filter the second drop box off the first one. The first one $box1 works fine. However I can’t get $box2 to build off the first. If I change
SELECT Site FROM companiesandsitessql WHERE Company ='$box1'");
to
SELECT Site FROM companiesandsitessql WHERE Company =”CompanyA);
it then pulls all the sites for CompanyA in the second box. I’ve tried many variations of $box1 but I must be missing something. Any ideas a appreciated.
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$con = mysql_connect($dbhost, $dbuser);
{
$box1 = array();
mysql_select_db('escalations');
$result = mysql_query("SELECT distinct Company FROM companiesandsitessql");
while($row = mysql_fetch_array($result)) { $box1[] = $row; }
}
/* Generate select box contents */
$out1 = '<select name="box1">';
$out1 .= '<option>Select Company</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$out1 .= '<option value="'.$v['Company'].'">'.$v['Company'].'</option>';
}
}
$out1 .= '</select>';
/* Output */
echo $out1;
{
$box2 = array();
mysql_select_db('escalations');
$result2 = mysql_query("SELECT Site FROM companiesandsitessql WHERE Company ='$box1'");
while($row2 = mysql_fetch_assoc($result2)) { $box2[] = $row2; }
}
/* Generate select box contents */
$out2 = '<select name="box2">';
$out2 .= '<option>Site list</option>';
if (!empty($box2)) {
foreach ($box2 as $k1 => $v) {
$out2 .= '<option value="'.$v['Site'].'">'.$v['Site'].'</option>';
}
}
$out2 .= '</select>';
/* Output */
echo $out2;
?>
Figured it out, here’s the code.
***File new.php***
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$con = mysql_connect($dbhost, $dbuser);
?>
<html>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function autoSubmit() {
$.post('dropoutput.php', { name: box1form.CompanyName.value},
function (output) {
$('#info').html(output).show();
});
}
</script>
<body>
<form name="box1form" action="insert.php" method="post">
<?php
{
$box1 = array();
mysql_select_db('escalations');
$result = mysql_query("SELECT distinct Company FROM companiesandsitessql ORDER BY Company ASC");
while($row = mysql_fetch_array($result)) { $box1[] = $row; }
}
/* Generate select box contents */
$CompanyName = '<select name="CompanyName" onchange="autoSubmit()">';
$CompanyName .= '<option selected="selected">Select Company</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$CompanyName .= '<option value="'.$v['Company'].'">'.$v['Company'].'</option>';
}
}
$CompanyName .= '</select>';
/* Output */
echo $CompanyName;
?>
<div id="info"></div><input name="send" type="submit" value="submit"><br>
</form>
</body>
</html>
***file dropoutput.php***
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
$name = mysql_real_escape_string($_POST['name']);
{
$box2 = array();
mysql_select_db('escalations');
$result2 = mysql_query("SELECT Site FROM companiesandsitessql WHERE Company ='$name' ORDER BY Site ASC");
while($row2 = mysql_fetch_assoc($result2)) { $box2[] = $row2; }
}
/* Generate select box contents */
$S = '<select name="SiteOptions[]" multiple="multiple">';
$S .= '<option>Site list</option>';
if (!empty($box2)) {
foreach ($box2 as $k1 => $v) {
$S .= '<option value="'.$v['Site'].'">'.$v['Site'].'</option>';
}
}
$S .= '</select>';
/* Output */
echo $S;
?>
***file insert.php...
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$dbpass = '';
$con = mysql_connect($dbhost, $dbuser);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo " Connected to database: ";
}
$Site = implode(', ', $_POST['SiteOptions']);
mysql_select_db("escalations", $con);
$sql="INSERT INTO escalationtrackersql (CompanyName, Site)
VALUES
('$_POST[CompanyName]', '$Site')";
echo "Added $_POST[CompanyName] ";
print $Site;
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo " : Escalation request successfully entered.";
mysql_close($con)
?>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
</head>
<body bgcolor="#C0C0C0">
<p> </p>
<p><a href="new.php">Return to the
escalation request form</a>.</p>
</html>