Multiple selection from two respective dropdown - php

I have two dropdown in html page.1st dropdown Contain Class-1, class-2,class3..
and 2nd dropdown contain StudentNameID for selected Classes. I wanted to multiple selection for classes in first dropdown and respective classes manage second dropdown selection for studentID.
1st Dropdown-want mutiple selection
<select>
<option value=".$row['classID'].">Class-1</option>
....like wise generate dropdown...
<option>Class-2</option>
<option>Class-3</option>
<option>Class-4</option>
</select>
2nd Dropdown-On selection of 1st dropdown show 2nd dropdown value.
<select> //same for 2nd dropdown list..
<option>StudentNameID1-Class-1</option>
<option>StudentNameID2-Class-1</option>
<option>StudentNameID1-Class-2</option>
<option>StudentNameID2-Class-2</option>
<option>StudentNameID3-Class-2</option>
<option>StudentNameID1-Class-3</option>
<option>StudentNameID2-Class-3</option>
<option>StudentNameID3-Class-3</option>
</select>
I want multiple selection is there and selected Id store in variable.So,by exploding I will use it on my next page where page redirect.
My question Is I want multiple selection fron both dropdowns.
If I choose Class-1 and Class-2 from 1st drop down then atomatic 2nd dropdown will shows related values from selected ClassID's.
Also same multiple selection for 2nd dropdown.
Can you please tell me How I will approched using php and java script?

What you are expecting is not a basic html element, it requires jquery integration as well.. Take css and js from https://github.com/harvesthq/chosen/releases/
Index.php as belwo:
<?php
require 'config.php';
$stmt = "SELECT id, ClassId from classes ORDER BY id DESC";
$query = $dbcon->query($stmt);
$results = ( $query ) ? $query->fetchAll(PDO::FETCH_ASSOC) : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>imaphpdeveloper#gmail.com</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/prism.css">
<link rel="stylesheet" href="css/chosen.css">
<style type="text/css" media="all">
/* fix rtl for demo */
.chosen-rtl .chosen-drop { left: -9000px; }
</style>
</head>
<body>
<form>
<div id="container">
<div id="content">
<h2><a name="multiple-select" class="anchor" href="#multiple-select">Multiple Select</a></h2>
<div class="side-by-side clearfix">
<div>
<em>Classes</em>
<select data-placeholder="Choose a Country..." class="chosen-select class-select" name="classes" multiple style="width:350px;" tabindex="4">
<option value=""></option>
<?php foreach($results as $result): ?>
<option value="<?php echo $result['id'];?>"><?php echo $result['ClassId'];?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<em>Students</em>
<select data-placeholder="Choose a Country..." class="student-select" name="classes" multiple style="width:350px;" tabindex="4">
<option value=""></option>
</select>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="js/chosen.jquery.js" type="text/javascript"></script>
<script src="js/prism.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script>
$('.class-select').change(function(){
var classId = $(this).val();
console.log(classId);
$.ajax({
url : 'getSub.php',
type: 'POST',
dataType : 'JSON',
data : {
'classId' : classId,
},
success : function(data){
var optionBox = '<option value=""></option>';
$.each(data, function(key, val){
optionBox += '<option value="'+val.id+'">'+val.StudentNm+'</option>';
});
$('.student-select').empty().append(optionBox);
console.log(optionBox);
}
});
});
</script>
</form>
And getSub.php as below:
<?php
require 'config.php';
$classIds = implode(',', $_POST['classId']);
$stmt = "SELECT id, StudentID, ClassID, StudentNm from students where ClassID IN ($classIds)";
$query = $dbcon->query($stmt);
$results = ( $query ) ? $query->fetchAll(PDO::FETCH_ASSOC) : '';
echo json_encode($results);
?>
Config.php:
<?php
$dbcon = new PDO("mysql:host=localhost;dbname=test", 'root', '');
?>

Not sure what you are asking but maybe this will help.
<form action="redirect_page.php" method="POST">
<input type="radio" name="class">
Class-1</input>
<input type="radio" name="class">Class-2</input>
<input type="radio" name="class">Class-3</option>
<input type="radio name="class4">Class-4</option>
</form>
On your second page do
$classes[]=$_POST['class'];
<select>
<?php
foreach($class as $num){
echo "<option>StudentNameID1".$num."</option>";
}
?>
</select>

Related

How to set value in dropdown that already been populated by mysql

i want to set value in bootstrap modal dropdown using jquery, that dropdown is also populated by mysql database, and when i select the any value from data table, model open and that selected value should already placed is modal drop down.picking up the value by jquery closest() function
this is where im getting the value of b_name
<td class="p_brand_name">Apple</td>
here is my Modal Code.
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">Brand</label>
<select class="form-control" name="p_brand_name" id="p_brand_name">
<option>Select Brand</option>
<option value="1">Apple</option>
<option value="2">Sony</option>
<option value="3">huawei</option>
<option value="4">Toshiba</option>
<option value="5">Dell</option>
<option value="6">Hp</option>
<option value="7">Samsung</option>
<option value="8">LG</option>
<option value="9">Aspire</option>
<option value="10">Lenovo</option>
<option value="11">Oppo</option>
<option value="14">Vivo</option>
<option value="16">Dawlance</option>
</select>
</div>
</div>
Here is my jquery code
var $row = $(this).closest('tr');
var b_name = $row.find('.p_brand_name').text(); // e.g it has value apple (b_name = apple)
console.log(p_id,b_name);
// $('select option[value='+b_name+']').prop({defaultSelected: true});
// $('#p_brand_name').val(b_name).attr('selected', 'selected');
// $('#p_sct_name').find($row.find('.p_sct_name').text()).attr('selected', 'selected');
// $('#p_color_name select').attr('value',$row.find('.p_color_name').text());
// $("#p_brand_name").val("b_name");
// $("#p_brand_name").get(0).selectedIndex = b_name;
// $("#p_brand_name").val(b_name).change();
// $("#p_brand_name")[b_name].selectedIndex=b_name;
// $('#p_brand_name').val(b_name).attr("selected", "selected");
// $('#p_brand_name').val(b_name).trigger("chosen:updated");
i have tried these all but none of this work
first of all i have demonstrated here how to get the option value and text on the change event of the select box:
$(document).ready( function(){
$('.form-control').on('change', function() {
let option_value = $(this).val();
let option_text = $(this).children("option:selected").text();
console.log(option_value, option_text);
});
});
Now, if i understand you correct, i hope, you want to file the select box like you have selected the option your self, well: in PHP you can do this like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<td class="p_brand_name">Apple</td>
<?php
$select_box_options = ['1' => 'Apple', '2' => 'Sony', '3' => 'huawei'];
?>
<form>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">Brand</label>
<select class="form-control" name="p_brand_name" id="p_brand_name">
<option>Select Brand</option>
<?php
foreach ($select_box_options as $value => $text) {
$selected = ($text === 'Apple') ? 'selected' : '';
?>
<option value="<?=$value?>" <?=$selected?>><?=$text?></option>
<?php } ?>
</select>
</div>
</div>
</form>
</body>
</html>
and in JQuery to fire event:
$('.form-control').val('2').trigger('change');

how to display select2 values in dropdown list using codeigniter?

I need to display the select2 values into my dropdown listbox using codeigniter framework in php.
for ex:
1)Dr. Abhay Nene
2)Dr. Ajoy Shetty
i have selected this name already. it showing in the list . but it not showing in the list as selected.
<select class="multiple-select2 form-control" name="reviwerid[]" multiple="multiple" id="userRequest_activity" required>
<?php
$cats = explode(',', $res->abstract_reviewerid);
print_r($cats);
echo $count_no = count($cats);
foreach($cats as $vald)
{
foreach($reviewresults as $reviewresult)
{
if($reviewresult->reviewer_name != "")
{ ?>
<option <?php ($vald == $reviewresult->reviewer_id) ? 'selected=' : '') ?> value="<?php echo $reviewresult->reviewer_id; ?>">
<?php echo $reviewresult->reviewer_name; ?></option>
<?php }
}
} ?>
</select>
please help me how to do this?
thanks in advance...!
[1]: https://i.s
this my php code:
tack.imgur.com/0K31f.jpg
Try this:
<link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css' />
<select multiple id="e1" style="width:400px">
<option value="1">Dr. Abhay Nene</option>
<option value="2">Dr. Ajoy Shetty</option>
</select>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<script type="text/javascript">
$("#e1").select2();
</script>

Dynamic dropdown list with PHP & MYSQL

I have been trying to create a form with dynamic dropdown list fetching data from MYSQL. My database is fine without errors.
The first category of dropdown is working fine but I am wondering why my 2nd dropdown is not working. I just cant trace any error in the code and yet this is happening. here's my code:
Code for dynamic dropdown form :
<?php
include_once "connection.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Dropdown Ajax</title>
</head>
<body>
<div class="country">
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value="">Select Country</option>
//populate value using php
<?php
$query = "SELECT * FROM country";
$results=mysqli_query($con, $query);
//loop
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo $country["country"];?></option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-
16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
</script>
<script>
function getId(val){
//We create ajax function
$.ajax({
type: "POST",
url: "getdata.php",
data: "cid="+val,
success: function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
Database connection code :
<?php
$con = mysqli_connect("localhost", "root", "kensift", "tuts");
//Check connection
if(mysqli_connect_errno()){
echo "Failed to connect:".mysqli_connect_errno();
}
?>
Code for 2nd dynamic dropdown :
<?php
include_once "connection.php";
if (!empty($_POST["cid"])) {
$cid = $_POST["cid"];
$query="SELECT * FROM city WHERE cid=$cid";
$results = mysqli_query($con, $query);
foreach ($results as $city){
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?>
</option>
<?php
}
}
?>
These three code parts are in different files.
I think your code is correct except forgot the quotations id "#cityList" .
It should be
$("#cityList").html(data);
I think your problem might be here:
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo
$country["country"];?></option>
<?php
}
Try and use this instead:
foreach ($results as $country){
echo'<option value="'.$country["cid"].'">'.
$country["country"].'</option>';
}

pre fill text fields (in form) based on value selected from dynamic drop down box

I will start off by saying I am new to coding so i find this very difficult, also i have asked a few questions recently, mainly because i am REALLY STUCK, so all help is really appreciated.
I have two tables. Employee (Employee_ID, First_name, Last_name, Address etc) and Training (Training_ID, Employee_ID, First_name, Last_name, Training_type).
For the training table, I have a form in which is meant to be filled out to assign a training type for an employee.
OK currently, the dropdown box,for employee ID, has the values of the employee ID from the employee table.
When i chose a value from the drop down box, i would like for the text fields in the form (firstname & Lastname) to update showing the names for that employee_id. I have searched online but have NO idea how to do this.
Below shows my form (php)
<html>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hrmwaitrose", $con);
?>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<title>Training</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Training</h1>
<form action="inserttraining.php" method="post">
<div>
<p>Training ID: <input type="text" name="Training_ID"></p>
<p>Employee ID:<select id="Employee_ID">
<?php
$result = mysql_query("SELECT Employee_ID FROM Employee");
while ($row = mysql_fetch_row($result)) {
echo "<option value=$row[0]>$row[0]</option>";
}
?>
</select>
<p>First name: <input type="text" name="First_name"></p>
<p>Last name: <input type="text" name="Last_name"></p>
<p>
Training required?
<select name="Training">
<option value="">Select...</option>
<option value="Customer Service">Customer Service</option>
<option value="Bailer">Bailer</option>
<option value="Reception">Reception</option>
<option value="Fish & meat counters">Fish & meat counters</option>
<option value="Cheese counters">Cheese counters</option>
</select>
</p>
<input type="submit">
</form>
</div>
</body>
</html>
And here is my php code for when the submit button is pressed.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hrmwaitrose", $con);
$sql="INSERT INTO training (Training_ID, Employee_ID, First_name, Last_name, Training)
VALUES
('$_POST[Training_ID]','$_POST[Employee_ID]','$_POST[First_name]','$_POST[Last_name]','$_POST[Training]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I think its done by java? not too sure.
Your view file:
<?php
// First of all, don't make use of mysql_* functions, those are old
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- You will need jQuery (or anyother javascript framework) to accomplish your goal cause you need ajax -->
<title>Training</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Training</h1>
<form action="inserttraining.php" method="post">
<div>
<p>
Training ID:
<input type="text" name="Training_ID">
</p>
<p>
Employee ID:
<select id="Employee_ID">
<option value="">Select one</option>
<?php
$st = $pdo->prepare("SELECT Employee_ID FROM Employee");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
?><option value="<?php echo $row ['Employee_ID']; ?>"><?php echo $row ['Employee_ID']; ?></option><?php
}
?>
</select>
<p>
First name:
<input type="text" name="First_name" id="First_name">
</p>
<p>
Last name:
<input type="text" name="Last_name" id="Last_name">
</p>
<p>
Training required?
<select name="Training">
<option value="">Select...</option>
<option value="Customer Service">Customer Service</option>
<option value="Bailer">Bailer</option>
<option value="Reception">Reception</option>
<option value="Fish & meat counters">Fish & meat counters</option>
<option value="Cheese counters">Cheese counters</option>
</select>
</p>
<input type="submit">
</form>
</div>
<script type="text/javascript">
$(function() { // This code will be executed when DOM is ready
$('#Employee_ID').change(function() { // When the value for the Employee_ID element change, this will be triggered
var $self = $(this); // We create an jQuery object with the select inside
$.post("getEmployeeData.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
})
});
})
</script>
</body>
</html>
Your getEmployeeData.php file:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
header("Content-Type:application/json; Charset=utf-8");
// As you can see, here you will have where Employee_ID = :employee_id, this will be
// automatically replaced by the PDO object with the data sent in execute(array('employee_id' => $_POST['Employee_ID']))
// This is a good practice to avoid SqlInyection attacks
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
Some last suggestions: indent the code correctly. Close every html tag (<input /> for example)
In a simple way, you hav to implement a little ajax method (with jQuery for example) who will be triggered on the onchange attribute of your dropdown list.
$('select').change(function() {
var choice = jQuery(this).val();
$.ajax({
url:'fakeurl.test.php',
type:'POST'
data : {'id' : choice},
success : function(response) {
$('input[name="First_name"]').val(response.firstname);
$('input[name="Last_name"]').val(response.lastname);
}
});
});
And of course, in your PHP
$id = $_POST['id'] ;
SELECT...WHERE employee_id = $id...
[...]
return json_encode(array(
'lastname'=>$employee_lastname,
'firstname'=>$employee_firstname
));

drop-down menu with php function

I've already created my html form with a drop-list menu of 5 selections
I want a selected option from the drop-list to call php function that will echo a selected option to the screen
<label>Fruits</label>
<select name="Fruits">
<option value="Ap">Apple</option>
<option value="BN">Banana</option>
<option value="OR">Orange</option>
For example, here is your html code
<html>
<head></head>
<title>Static Dropdown List</title>
<body bgcolor="pink">
Employee List :
<select>
<option value="Select">Select</option>}
<option value="Moyed">Moyed Ansari</option>
<option value="Asad">Asadullah</option>
<option value="Usman">Usman Ali</option>
</select>
</body>
</html>
Now You will use the above table in the dropdown list using the following code.
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<BODY bgcolor ="pink">
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Employee List :
<select Emp Name='NEW'>
<option value="">--- Select ---</option>
<?
mysql_connect ("localhost","root","");
mysql_select_db ("company");
$select="company";
if (isset ($select)&&$select!=""){
$select=$_POST ['NEW'];
}
?>
<?
$list=mysql_query("select * from employee order by emp_id asc");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<? echo $row_list['emp_id']; ?>"<? if($row_list['emp_id']==$select){ echo "selected"; } ?>>
<?echo $row_list['emp_name'];?>
</option>
<?
}
?>
</select>
<input type="submit" name="Submit" value="Select" />
</form>
</body>
php is on the server side
where as all the html is on the user side..
if you want to echo the selected option, then you have to send the selected option to the server side using Ajax Request or using some other technique like POST a form.
// using jquery you can get your selected value
<script>
var selected_value = $("#idOfTheSelectTag").val();
// or you can also do
var selected_value = $("#idOfTheSelectTag :selected").text();
// now you can post it to the php page using AJAX where you can echo it
$.post('page_name.php', {SELECTED_VALUE : selected_value}, function(data){
// on the server side in page_name.php file if you echo the value then it will be returned in the data object in the function
});
</script>

Categories