Populate a text box using a selected value in a dependent dropdown - javascript

I have this two tables in my database
1 - tbl_category
2 - tbl_shelf_place
(I want to achieve this kind of output where the selected category_name from the drop-down (book_category) with a value of category_id will show the shelf_code in a textbox instead of a DROPDOWN, based on the equivalent shelf_id).
-------------------------- -------------------------
tlb_category tbl_shelf_place
--------------------------- -------------------------
category_id | category_name shelf_id| shelf_code
--------------------------- -------------------------
1 | General Works 1 | General Works Shelf
2 | History 2 | History Shelf
Below is my current code for the dependent dropdown.
My dropdown code in HTML
<select id="book_category" name="book_category" class="selectpicker" data-style="btn btn-danger" onChange="getState(this.value);" required>
<option disabled selected value=""> Choose Category
</option>
<?php
$query = "SELECT category_id , category_name FROM tbl_category";
$stmt = $mysqlconnection->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($category_id , $category_name);
while($stmt->fetch())
{
$getcategoryID = $category_id;
$getcategoryname = $category_name;
echo "<option value='{$getcategoryID}'>{$getcategoryname}</option>";
}
?>
</select>
<select id="book_shelf" name="book_shelf" class="selectpicker" data-style="btn btn-danger" required>
<option disabled selected value="">
</option>
</select>
My script code
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "dropdownrequest.php",
data:'category_id='+val,
success: function(data){
$("#book_shelf").html(data);
}
});
}
</script>
dropdownrequest.php
<?php
include_once ("../database/dbconnect.php");
if(!empty($_POST["category_id"])) {
$query ="SELECT * FROM tbl_shelf_place WHERE shelf_id = '" . $_POST["category_id"] . "'";
$results = $mysqlconnection->query($query);
?>
<?php
foreach($results as $shelf) {
?>
<option value="<?php echo $shelf["shelf_id"]; ?>"><?php echo $shelf["shelf_code"]; ?></option>
<?php
}
}
?>

You can use this code.
<select id="book_category" name="book_category" class="selectpicker" data-style="btn btn-danger" onChange="getState(this.value);" required>
<option disabled selected value=""> Choose Category
</option>
<?php
$query = "SELECT category_id , category_name FROM tbl_category";
$stmt = $mysqlconnection->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($category_id , $category_name);
while($stmt->fetch())
{
$getcategoryID = $category_id;
$getcategoryname = $category_name;
echo "<option value='{$getcategoryID}'>{$getcategoryname}</option>";
}
?>
</select>
<textarea id="book_shelf" name="book_shelf"></textarea>
In your JS.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "dropdownrequest.php",
data:'category_id='+val,
success: function(data){
$("#book_shelf").val(data);
}
});
}
</script>
In you PHP code.
<?php
include_once ("../database/dbconnect.php");
if(!empty($_POST["category_id"])) {
$query ="SELECT * FROM tbl_shelf_place WHERE shelf_id = '" . $_POST["category_id"] . "'";
$results = $mysqlconnection->query($query);
$shelf_text = '';
foreach($results as $shelf) {
$shelf_text .= $shelf["shelf_id"]." - ".$shelf["shelf_code"];
}
echo $shelf_text;
exit;
}
?>
Hope this will give you and Idea. I haven't tested this code so please pardon if there is any syntax error. Also tweak the code in PHP file so you can show the shelf_code and shelf_id as per your requirements.

You can do it like this, one way to achieve this
PHP
<?php
include_once ("../database/dbconnect.php");
if(!empty($_POST["category_id"])) {
$query ="SELECT * FROM tbl_shelf_place WHERE shelf_id = '" .
$_POST["category_id"] . "'";
$results = $mysqlconnection->query($query);
foreach($results as $shelf){
echo $shelf["shelf_code"];
}
}
?>
No need to return option now. Just read the data returned and add it to your textbox element in HTML
HTML
<select id="book_category" name="book_category" class="selectpicker" data-
style="btn btn-danger" onChange="getState(this.value);" required>
<option disabled selected value=""> Choose Category</option>
<?php
$query = "SELECT category_id , category_name FROM tbl_category";
$stmt = $mysqlconnection->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($category_id , $category_name);
while($stmt->fetch())
{
$getcategoryID = $category_id;
$getcategoryname = $category_name;
echo "<option value='{$getcategoryID}'>{$getcategoryname}
</option>";
}
?>
</select>
// Add HTML Textbox here
<input type="text" id="book_shelf">
Rest of the code should be same.

Related

PHP query of columns with value from <select> MySQL

I am trying to create a list populated with the columns from a table previously selected from another list of tables. But, I can't get the query to work.
I've appended a sample of my code that is not working. If i replace ".$search_query." with a table name it works. But, I want it to use the table selected by the user.
<!-- Table Select -->
<form name="myform" action="" method="post">
<select id="parentTable_{{$index}}" name="parentTable_{{$index}}" ng-model="parentTable_$index" type="selectable" onchange="submitform();">
<option style="display:none" value="users">select a table</option>
<?php
$count=1;
$sel_query="SHOW TABLES";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row["Tables_in_yamanagolddb"]; ?>"><?php echo $row["Tables_in_yamanagolddb"]; ?></option>
<?php $count++; } ?>
</select>
</form>
<!-- Index reference -->
<?php $search_query = mysqli_real_escape_string($con, $_POST['parentTable_{{$index}}']); ?>
<!-- Field Select -->
<select ng-model="parentField_$index" type="selectable">
<option style="display:none" value="">select a field</option>
<?php
$count=1;
$sel_query="select * from information_schema.columns where table_name = '".$search_query."' and table_schema = 'yamanagolddb'";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row["COLUMN_NAME"]; ?>"><?php echo $row["COLUMN_NAME"]; ?></option>
<?php $count++; } ?>
</select>
<script>
function submitform()
{
document.myform.submit();
}
</script>

PHP Value Repeat Twice

My project so far I'm grabbing data from my SQL table. I have four different sections which all grab the same information from the same table.
The first section works great. The data is there.
The next three sections works, BUT the data repeats itself which I don't understand why or how I can fix it. Below are my SQL table and my php code.
+--------+
| Color |
+--------+
| Red |
| Blue |
| Orange |
| Black |
+--------+
+-----------+--------------+-----------+
| GroupName | MemberName | ValueName |
+-----------+--------------+-----------+
| Red | Joe Bob | Joe |
| Red | Catherine | Kat |
| Blue | Tommy | Tom |
| Orange | John Razks | John |
| Black | Trevor Smith | Trevor |
+-----------+--------------+-----------+
Code:
<form id=#blah>
<select id="committee" name="committee" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select Color</option>
<?php
$conn = mysqli_connect("#connection");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
while ($row = mysqli_fetch_assoc($result)){
unset($committee, $Committee);
// $committee = $row['Committee'];
$Committee = $row['Color'];
echo '<option value=" .$Committee. ">'.$Committee.'</option>';
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
$conn = mysqli_connect("#connection");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT distinct MemberName,GroupName,ValueName from Members order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
$array[$row['GroupName']][] = $row;
}
foreach($array as $class => $value){
if(is_array($value)){
echo "<optgroup class=".$class.">";
foreach($value as $k=>$v){
echo "<option value=".$v['ValueName'].">".$v['MemberName']."</option>";
}
echo "</optgroup>";
}
}
?>
</select>
</form>
<form id=#id>
<select id="committee" name="committee" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select Color</option>
<?php
$conn = mysqli_connect("#connection");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
while ($row = mysqli_fetch_assoc($result)){
unset($committee, $Committee);
// $committee = $row['Committee'];
$Committee = $row['Color'];
echo '<option value=" .$Committee. ">'.$Committee.'</option>';
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
$conn = mysqli_connect("#connection");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT distinct MemberName,GroupName,ValueName from Members order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
$array[$row['GroupName']][] = $row;
}
foreach($array as $class => $value){
if(is_array($value)){
echo "<optgroup class=".$class.">";
foreach($value as $k=>$v){
echo "<option value=".$v['ValueName'].">".$v['MemberName']."</option>";
}
echo "</optgroup>";
}
}
?>
</select>
</form>
I'm not 100% sure, but I think the duplication comes from using the same variable names in your loops when recalling the same query the second time or it could also be something happening in the loops.
I think you could avoid this and make the code a bit neater by running each query only once and then call the data each time you need to use it:
<?php
$conn = mysqli_connect("localhost","user","pass","db_name");
if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
else{
$color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
$colors = array();
while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
$member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName,ValueName from Members order by MemberName ASC");
$members = array();
while ($row = mysqli_fetch_assoc($member_result)){
if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
$members[$row['GroupName']][] = $row; }
}
?>
<form id=#blah>
<select id="committee" name="committee" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select Color</option>
<?php
foreach($colors as $color){
echo "<option value=\"".$color."\">".$color."</option>";
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
foreach($members as $key => $member_group){
echo "<optgroup class=\"".$key."\">";
foreach($member_group as $val){
echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
}
echo "</optgroup>";
}
?>
</select>
</form>
<form id=#id>
<select id="committee" name="committee" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select Color</option>
<?php
foreach($colors as $color){
echo "<option value=\"".$color."\">".$color."</option>";
}
?>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">
Individual:
<select name="senator" id="senator">
<option value="">Select Individual</option>
<?php
foreach($members as $key => $member_group){
echo "<optgroup class=".$key.">";
foreach($member_group as $val){
echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
}
echo "</optgroup>";
}
?>
</select>
</form>
This should let you get the desired output while only having to run each query once and should eliminate the duplication. I hope this helps

Add more fields function and populate second combobox based on first combobox can be run for all row insert

I have jQuery PHP function to add more fields.
HTML
<div class="faculty_row">
<select name="search_category" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<input type="text" name="message[]">
</div>
Add More
JS
jQuery(document).ready(function($){
$("#add_more").on('click', function(e){
e.preventDefault(); // Prevent Default the event
var clone = $(".faculty_row").eq(0).clone(); // clone only first item
$("#faculty_wrapper").append(clone); // append it to our form
});
Then I have jQuery Populate Second Combobox based on First Combobox
html
<select name="search_category" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<span id="show_sub_categories" align="center">
JS
jQuery(document).ready(function($){
$('#loader').hide();
$('#show_heading').hide();
$('#search_category_id').change(function(){
$('#show_sub_categories').fadeOut();
$('#loader').show();
$.post("get_chid_categories.php", {
parent_id: $('#search_category_id').val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
});
return false;
});
function finishAjax(id, response){
$('#loader').hide();
$('#show_heading').show();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function alert_id()
{
if($('#sub_category_id').val() == '')
alert('Please select a sub category.');
else
alert($('#sub_category_id').val());
return false;
}
Each function is run perfectly. How can I combine that 2 function to be 1? So the populate Second Combobox based on First Combobox can be run on next row if I click button Add More.

onchange function when selecting drop down menu will populate a textbox

this is my table in the database
tbl_job_title
ID | Job_title | description |
1 | Accountant | Handle Accounts |
2 | Dev. Support | Support Centre |
when selecting the job title from the table, i'm using a drop down menu and here is my code.
<select id="job_title" >
<option value=""> </option>
<?php foreach ($job_title as $row): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?>
</option>
<?php endforeach?>
</select>
and I have a textbox that will populate if i select a job_title
<input type="text" id="catch_value">
How do I populate the textbox when I select example is "Accountant", the textbox value must be "Handle Accounts".
Here is the short & sweet code I have made just for you, feel free to use it!
Not required Ajax...
CODE -
<select id="job_title" >
<option value="" class="job" role=""> </option>
<?php foreach ($job_title as $row): ?>
<option value="<?php echo $row['id']; ?>" class="job<?php echo $row['id']; ?>" role="<?php echo $row['description']; ?>"><?php echo $row['title']; ?>
</option>
<?php endforeach?>
</select>
Jquery -
$('#job_title').on('change',function(){
var m = this.value;
var n = $('.job'+m).attr('role');
$('#catch_value').val(n);
return false;
});
eg - fiddle
<select id="job_title" onchange="javascript:callajaxvalue(this.value);">
<option value=""> </option>
<?php foreach ($job_title as $row): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?>
</option>
<?php endforeach?>
</select>
<script>
function callajaxvalue(id)
{
$.ajax({
type: "POST",
url: "some.php",
data: { id: id}
success: function(data, textStatus ){
if(data)
{ $("#catch_value").val(data);}
},
})
}
</script>
some.php
$_POST['id'];
$query = "get data from table";
execute query.
echo $row['description'];
For codeigniter
function callajaxvalue(id)
{
$.ajax({
type: "POST",
url: "my_controller/update/"+id,
data: { id: id}
success: function(data, textStatus ){
if(data)
{ $("#catch_value").val(data);}
},
})
}
my_Controller.php
public function update()
{
$id = $this->input->post('id');
$data['discription'] = call model function for get data form database
echo json_encode($data);
}
$('#job_title').change(function(){
$('#catch_value').val('Handle Accounts');
});
see fiddle:fiddle
or you can add if statments
$('#job_title').change(function(){
var jt = $('#job_title').val();
if(jt == "Something")
{
$('#catch_value').val('Handle Accounts');
}
if (jt == "SomethingElse")
{
$('#catch_value').val('somethingelse');
}
});
This is the right answer :
<select id="job_title" onchange='populate()'>
<option value=""> </option>
<?php foreach ($job_title as $row): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?>
</option>
<?php endforeach?>
</select>
<script>
function populate(){
var jobttl= document.getElementById('job_title').value();
if(jobttl){
document.getElementById('catch_value').value;
}
}
</script>

Dynamic Dropdowns POST

I'm trying to post the values that I get from each dropdown menu, this is an n-level, however I'm going to use them maximum of 3. How can I post every value i get from each selection?
<?php
include('dbcon.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from ajax_categories where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
?>
http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
change the select option of your like this
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
while ($rows = mysql_fetch_assoc(#$results))
{?>
echo '<option value="'.$row['id'].'">'.$rows['category'].'</option>';
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
</select>

Categories