I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output
Related
I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>
I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>
I am using Materialize CSS as my CSS framework and I also wasted 1 hour searching for the answers in google/stackoverflow etc.. but I can't seem to find the answer to solve this problem. So, what I am doing is I'm trying to pass the value of Select 1 to Select 2. Here is my code below
Select 1:
<select id="Accounts">
<option value="">Choose Account to edit</option>
<?php
$query = "SELECT * FROM personnel_list WHERE status = ?";
$result = $this->db->query($query, array("Active"))->result_array();
foreach ($result as $row) {
extract($row);
echo "<option value=\"$id-$name-$position-$status\">$name</option>";
}
?>
</select>
Select 2:
<select id="editPosition">
<option value="">Choose Position</option>
<?php
$Position = array("Manager", "Supervisor", "Assistant Manager", "Assistant Supervisor")
for ($x=0; $x < count($Position); $x++) {
echo "<option value=\"$Position[$x]\">$Position[$x]</option>";
}
?>
</select>
<label for="editPosition">Position:</label>
JS:
$("#Accounts").change(function(){
var accval = $(this).val().split("-");
var id = accval[0];
var name = accval[1];
var post = accval[2];
var status = accval[3];
$("#editPosition").val(post);
})
Other JS that I have tried is:
$("#editPosition option[value='"+post+"']").prop("selected", true);
Rendered Select 1:
<select id="Accounts">
<option value="">Choose Account to edit</option>
<option value="1-John-Manager-Active">John</option><option value="2-Mark-Assistant Manager-Active">Mark</option>
</select>
Rendered Select 2:
<select id="editPosition">
<option value="">Choose Position</option>
<option value="Manager">Manager</option>
<option value="Supervisor">Supervisor</option>
<option value="Assistant Manager">Assistant Manager</option>
<option value="Assistant Supervisor">Assistant Supervisor</option>
</select>
Thanks in advance for those who will answer and help me!
Use event delegation to listen for changes on the Accounts select instead:
$("#Accounts").on("change", function(){
var accval = $(this).val().split("-");
var id = accval[0];
var name = accval[1];
var post = accval[2];
var status = accval[3];
$("#editPosition").val(post);
});
See this jsFiddle for a working example.
Materialize CSS does a lot of modifications to the DOM when it renders its components, making straightforward JavaScript operations on UI elements from your part break at times.
I want to select the specific option in drop down list when a condition is existed.I set the Session in php and if the combo box has the value of 1 , it will be shown the option with value 1. I mean if session is 1, select the option with value of 1, if session is 2, select the option with vlaue of 2, and so on... . I want to set automatically select(I see the changes) with session in php.
sth like blewo:
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//must be shown the option with value of `1`.
<script>
Try this .
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//set local variable value so that I don't have to do it for each of the following ways to do this.
var num = "<?php echo $_SESSION['num']; ?>";
//normal javascript
document.getElementById("sel").value = num;
//using jQuery
$("#sel").val(num);
<script>
Or this try vikingmaster's way
You don't necessarily need js to do this. You can simply use php since you're already grabbing the num from the session.
Easiest way to do it would be:
<select id="sel" >
<?php if($_SESSION['num'] == 1): ?>
<option value='1' selected>one</option>
<?php else: ?>
<option value='1'>one</option>
<?php endif; ?>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
But if you want to use javascript(jQuery in particular here), you can do something like this:
<script>
$(document).ready(function(){
var num = <?php echo $_SESSION['num']; ?>;
$('#sel > option').each(function(){
if($(this).val() == num){
$(this).prop('selected', true);
}
});
});
</script>
Here's a fiddle.
There are a lot of ways to do this. This is what approach I would take, I'm sure others can provide just as viable or probably better answers.
Just set the value with the selected attribute
<select id="sel" >
<option value='1' selected>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//alternately, set it explicitly
var element = document.getElementById('sel');
element.value = 1;
<script>
<select id="sel" >
<option value='1' <?php if($_SESSION['num']=='1') echo "selected"; ?> >one</option>
<option value='2' <?php if($_SESSION['num']=='2') echo "selected"; ?> >two</option>
<option value='3' <?php if($_SESSION['num']=='3') echo "selected"; ?> >three</option>
</select>
I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()"> <!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()"> <!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
The question I have is: how to get the selected values from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?
So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:
Post the form to itself (as you have chosen) or
use ajax (possibly via jQuery for quickness).
(both of these examples don't address how you are accessing the database)
1)
Using your run function:
<script type="text/javascript">
function run(){
document.getElementById('form1').submit()
}
</script>
Additional PHP:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
echo "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
}
}
else
{
echo "<option>Please choose a department and a type of hire</option>";
}
?>
2)
<script type="text/javascript">
function run(){
$.post('get_employees.php',$('form1').serialize(),function(data){
var html = '';
$.each(data.employees,function(k,emp){
$('select[name="employees"]').append($('<option>', {
value: emp.name,
text: emp.name
}));
.html(html);
},"json");
}
</script>
And get_employees.php would contain something like:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
$return = array();
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
$return[]['name'] = $row_list['name'];
}
echo json_encode($return);
}
?>
Note, these are just quickly written examples. A lot more could/should be done here.
Heres a modified jQuery version of your code. (With some cleanup)
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()">
<!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()">
<!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<? if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>
Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...
<script type="text/javascript">
$('#type_hire').change(function() {
var selected = $('#type_hire option:selected'); //This should be the selected object
$.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
//Now data is the results from the DropdownRetrievalScript.php
$('select[name="employees"]').html(data);
}
}
</script>
Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.
Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.