How to populate second drop down box on first drop down (Hard) - javascript

I want to populate my second drop down box based on what value the user has chosen on the first. This is what I have done so far:
In the PHP file:
function displayDropDown()
{
$table_tester = "TBL_TESTER_LIST";
$query_string = "select * from $table_tester";
$result = #mysql_query($query_string) or die (mysql_error());
echo "<select id=\"tester_type\" onChange=\"getTesterType();\">";
while($data = mysql_fetch_array($result))
{
$tester_type = $data['tester_type'];
echo "<option value='$tester_type'>$tester_type</option>"; // first drop down
}
echo "</select>";
}
function displaySecondDropDown($selected_tester_type)
{
$table_tester = "TBL_TESTER_LIST";
$query_string = "select * from $table_tester where tester_type = '$selected_tester_type'";
$result = #mysql_query($query_string) or die (mysql_error());
echo "<select>";
while($data = mysql_fetch_array($result))
{
$tester_name = $data['tester_name'];
echo "<option value='$tester_name'>$tester_name</option>";// second drop down
}
echo "</select>";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="insert")
{
$tester_type = rtrim($_REQUEST['tester_type']);
$tester_name = rtrim($_REQUEST['tester_name']);
echo checkDuplicateTesterName($tester_type, $tester_name);
}
else if($action=="displayDropDown")
{
$selected_tester_type = $_REQUEST['tester_type'];
echo displayDropDown();
echo displaySecondDropDown($selected_tester_type);
}
?>
In the external JavaScript file:
function displayDropDown()
{
var page = "database.php";
$.post(page, {
action : "displayDropDown"
}, function(data) {
$("div#drop_two_list").html(data);
});
}
function getTesterType()
{
var tester_type = $("#tester_type").val();
var page = "database.php";
$.post(page, {
tester_type : tester_type
}, function(data) {
$("div#drop_two_list").html(data);
});
}
In the HTML file:
<html>
<head>
<title>Delete Tester</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript">displayDropDown();</script>
</head>
<body>
<h3>Delete Tester</h3>
<div id="drop_two_list"></div>
<table class="deleteTable">
<tr>
<td/><td><br>
<input type="button" value="Cancel" onclick="window.close();"/>
<input type="button" name="send" value="Delete" onclick="deleteTester();"/>
</td>
</tr>
</table>
</body>
</html>
Two drop down boxes do appear. The first one has values(which are wrong I'll explain in the later part) and the second is empty. Also, an error appeared: Notice: Undefined index: tester_type in /opt/lampp/htdocs/Signup/module1/database.php on line 86 which is $selected_tester_type = $_REQUEST['tester_type']; in the PHP file. If I were to select a value in the first one then another error would replace everything on the page with: Notice: Undefined index: action in /opt/lampp/htdocs/Signup/module1/database.php on line 75 which is $action = rtrim($_REQUEST['action']);.
Now onto the part where I state why the first drop down box has the wrong values. Before proceeding, to understand my question better here is the table(TBL_TESTER_LIST) that I am trying to populate the drop down boxes with.
Note: I am only showing 5 sample rows in random order because I have more than 500 rows in this table and wouldn't want to put everything here.
id tester_type tester_name
1 LMX LMX-01
2 LMX LMX-04
26 LCX LCX-06
40 CAT CAT-14
95 HPPS HPPS-01
The tester_type column is what I want to populate my first drop down box with, and tester_name column is what I want to populate my second drop down box with, accordingly. As you can see, there duplicates for tester_type because one tester_name can belong to the same tester_type(An example would be green apple no.1(tester_name) is an apple(tester_type) and green apple no.2(tester_name) is also an apple(tester_type)).
What I am currently getting in my first drop down box is just: LMX, LMX, LMX, LMX, and so on. That is because my first 31 Rows are LMX. How do I code my drop first down box such that it would only display one of each type, and my second drop down box would display the values that are based on what the user selected?
An example would be: If the user selects LMX in the first drop down box, then all the tester_names that are LMX tester_type would populate the second drop down box.
If more information needed on the table, please do tell me. Been searching for a solution for 5 days and I don't seem to be close to a conclusion.

Without asking why your table is structured that way, would it not be enough to use the DISTINCT clause in your query to eliminate duplicates.
select DISTINCT tester_type from $table_tester

Related

The first table row (dynamically generated) always shows, no matter the input value for Javascript

Sorry for asking, I am probably missing something small here but have no clue. I dynamically generated a long list of radio buttons using PHP. On top of the list is an HTML input to search through the list using jQuery. This works, except for one tiny detail. The first radio button in the list always shows, no matter what the search result is. Even if I type something completely different, I will always see the first radio button in the list together with the matching results.
What is going wrong here?
This is my dynamically generated list of radio buttons, using HTML and PHP:
<input id="addplantSearch" class="form-control" type="text" name="addplantsearch" placeholder="Zoek op (Latijnse) naam..." style="margin:0; height:48px;"> <!-- Search input -->
<?php
$query = "SELECT * FROM plants ORDER BY plants.name ASC;";
$post_data = $data->execute($query);
// Prepared statement in 'execute' method (Database class)
?>
<div class="addplant-list">
<?php
foreach ($post_data as $post) {
# Loop start
?>
<div class="searchable">
<label class="pselect-container"> <?php echo $post['name']; ?>
<input type="radio" name="selectPlant" value="<?php echo $post['plant_id']; ?>">
<span class="pselect-checkmark" style="width:100%;">
<img src="../system/src/img/plants/<?php echo $post['directory']; ?>/icon.png" />
<?php echo $post['name'] . " - (" . $post['name_latin'] . ")"; ?>
</span>
</label>
</div>
<?php
# Loop end
}
?>
</div>
And this is my jQuery, responsible for searching through the list:
$("#addplantSearch").keyup(function() {
var value = this.value;
$(".addplant-list").find(".searchable").each(function(index) {
if (!index) return;
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
EDIT: The first item in the list is determined by the alphabetical order (ASC) of my database results (see $query variable). So this is always the same item in alphabetical order.
It looks like your issue is with your if statement.
if (!index) return;
This problem occurs because JavaScript uses 0 based arrays, and 0 is also a falsy value. Meaning:
!0 === true
and the first item in the array will always return out of the function and won't be applicable to the toggle logic.
So probably a lot of ways to work around this, one would be to check the length of the array before the each function. Ex:
$("#addplantSearch").keyup(function() {
var value = this.value;
var searchableItems = $(".addplant-list").find(".searchable");
if (searchableItems.length) {
searchableItems.each(function(index) {
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
}
});

Output Data From MYSQL Table Into HTML Form Depending On User Choice

I have a MYSQL table (roomcost) that holds the costs of hiring rooms.
costID Room Cost
1 room1 15
2 room2 30
3 room3 50
rsRoomCost SQL is: SELECT * FROM roomcost
The HTML form has checkboxes that allow the hirer to make the choice of Room 1, Room 2 or Room 3. The hirer can hire one, any two or all three rooms.
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</div>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</div>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</div>
The form also has an input box (that will be hidden, once I get it working) for each room that will be filled with the appropriate cost from the table. When the form is submitted, the hirers record would hold the choice of room(s) and cost paid by that hirer at the time of hiring.
The JS script that checks if a particular checkbox is selected and would output the cost to the relevant input box.
function Check() {
if (document.forms["bookform"].room1.checked) {
document.forms["bookform"].thisRoom1.value = "<?php echo($row_rsRoomCost['room1']; ?>";
} else if (document.forms["bookform"].room2.checked) {
document.forms["bookform"].thisRoom2.value = "<?php echo($row_rsRoomCost['room2']; ?>";
} else if (document.forms["bookform"].room3.checked) {
document.forms["bookform"].thisRoom3.value = "<?php echo($row_rsRoomCost['room3']; ?>";
}
}
The input boxes for the output are:
Room 1: <input type="text" name="thisRoom1" value="">
Room 2: <input type="text" name="thisRoom2" value="">
Room 3: <input type="text" name="thisRoom3" value="">
As you see, I'm trying to use php to fill in the relevant value from the database table. However, this, of course, only shows the cost from the first record in the costs table regardless of which room is checked.
How do I get the cost of the chosen room from the table into the correct input box on the form?
I've tried <?php echo($row_rsRoomCost['room1']) where ($row_rsRoomCost['costID']) = '1'; ?> but this doesn't work. I thought about 'case' statements but don't know how that would work. The only way I can think of is a seperate SQL statement for each room. eg: SELECT * FROM roomcost WHERE costID = 1
How do I get the cost of the selected room from the table into the correct input box on the form?
Going through your code I find that that would be the long way round of solving it .
The first step to solving it would be to put your data into a reusable front End source like JSON (it easier to work with ).
Example: (Results are in the console log F12)
<?php
$servername = "localhost";
$username = "root";
$password = "jono23";
$dbname = "helpothers";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `roomcost`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// echo "id: " . $row["costID"]. " - Name: " . $row["room"]. " " .$row["cost"]. "<br>";
// data you want to send to json
$data[] = array(
'id' => $row['costID'],
'room' => $row['room'],
'cost' => $row['cost']
);
//}
}
} else {
echo "0 results";
}
$conn->close();
$json_data = json_encode($data);
//print_r($json_data);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id='bookform' >
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</input>
<input type="text" name="room1value" readonly><br>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</input>
<input type="text" name="room2value" readonly><br>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</input>
<input type="text" name="room3value" readonly><br>
</form >
<script type="text/javascript">
var Rooms = JSON.parse('<?php print_r($json_data) ; ?>');
console.log(Rooms);
function Check() {
//room1
if (document.forms["bookform"].room1.checked)
{
document.forms["bookform"].room1value.value = Rooms[0].cost;
console.log(Rooms[0].cost);
}else{
document.forms["bookform"].room1value.value ='';
}
//room2
if (document.forms["bookform"].room2.checked)
{
document.forms["bookform"].room2value.value = Rooms[1].cost;
console.log(Rooms[1].cost);
}else{
document.forms["bookform"].room2value.value ='';
}
//room3
if (document.forms["bookform"].room3.checked)
{
document.forms["bookform"].room3value.value = Rooms[2].cost;
console.log(Rooms[2].cost);
}else{
document.forms["bookform"].room3value.value ='';
}
}
</script>
</body>
</html>
By encoding the SQL query results into a json array first you able to
close the database connection so not to use up unnecessary resources
on multiple requests
Then By calling that PHP JSON Object into JavaScript you can more easily apply it to your html and JavaScript Needs
Converting PHP Data To JSON and parse with JavaScript Help us work with things like rest api's
This is the main reason why JSON implementation can be found in many languages as its an easy way to share data across different coding languages
Another suggestion that I would make for the handling of the data is not to store the values in a checkboxes . Create another text input for that purpose and store them there . e.g
<input type='text' id='gethandle1'>
<script>
let box1 = document.getElementById('gethandle1');
box1.value = Rooms[0].cost;
</script>
I hope this helps you .

Using auto complete textbox get table record from mysql database and shows in text fields

I need to access the table record from the database when they press enter in the autocomplete textbox (at the time of select value), and it shows data in text element.
I have tried this code but cannot get the whole record:
html code:
<input class="form-control" name="sel_product_name" id="sel_product_name" >
<input class="form-control" name="sel_product_id" id="sel_product_id">
javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_product_name").autocomplete({
source:'autocomplete.php',
minLength:1
});
});
</script>
autocomplete.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("es_restaurant");
$term=$_GET["term"];
$query=mysql_query("SELECT fld_product_id,fld_product_name
FROM tbl_product_master_header
where fld_product_name like '%".$term."%' ");
$json=array();
while($product_name=mysql_fetch_array($query))
{
$json[]=array(
'value'=> $product_name["fld_product_name"]
//I want to add one more column value to display fld_product_id in
//another text box
);
}
echo json_encode($json);
?>
Try hanging the code to this:
$json = array();
while($product_name=mysql_fetch_array($query)) {
$json[]= $product_name["fld_product_name"];
}
echo json_encode($json);
I think because you are adding another layer to the array it is not working.
http://jqueryui.com/autocomplete/ shows using an array without keys.
http://www.smarttutorials.net/jquery-autocomplete-search-using-php-mysql-and-ajax/ also confirms this.
As to your comment try this:
while($product_name=mysql_fetch_array($query)) {
$json[]= array('id' => $product_name["fld_product_id"],
'value' => $product_name["fld_product_name"]);
}
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

PHP: print from a list of data (loop difficult)

Hi i have a little problem,my code create a list of buttons and each button have a name(value) from my list (table 'usernames')
....for exemple (table 'usernames' have 3 lines aa-bb-cc my code make 3 button with values aa & bb & cc..............
so what i want to do, is when i click on a button i want to print the value of this button in a div, for exemple if i click on the button who have the value 2 i want to print 2 in the div(i have a problem whit my loop, and i need help please)
this is my code:
$conn=mysqli_connect("localhost", "root", "pwd","sn") or die(mysqli_error());
$que2=mysqli_query($conn,"select usernames from posts", MYSQLI_USE_RESULT); // return a lot of lines on 'usernames'
$re=0;
$datax=array();
$i=0;
while ($r = mysqli_fetch_array($que2))
{
$re = $r["cnt"];
$datax[$i]=$re;
?>
<input id="ppost" name="ppost" value="<?php echo $datax[$i]; ?>" type="submit">
<br>
<script type="text/javascript">
$(function(){
$('#ppost').click(function(){
alert("<?php echo $datax[$i]; ?>");
});
});
</script>
<?php
$i++;
}
Ok, so there're few things to have a look at:
take the <script> out of the loop - one script can take care of all the buttons
you can't give same ID to all your inputs - id="..." has to be unique throughout your script
the JS script (assuming you have jQuery included prior to your ) should be:
<script type="text/javascript">
$(function(){
$('input[type="submit"]').click(function(){
alert($(this).attr('value'));
});
});
</script>
this should do the trick, let me know if this is what you wanted.

Pass checkbox value to Edit (using href)

I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']

Categories

Resources