My situation is, I have 2 drop-down list and only one data from one of the drop-down list will be sent into the second page. That's mean, the data from another drop-down list will not be sent. So, I choose to display the drop-down list by using the radio button. If I choose the 1st button, it will only display the 1st drop-down list and vice versa.
The problem is, when I choose the 1st drop-down list, it doesn't send any POST data from the drop-down list to the second page, only blank. But, if I choose the 2nd drop-down list, it send the data properly! I thought that there are errors in 1st drop-down list codes (even both codes are practically identical). So, I add another list, and this time, only the 3rd drop-down list's data is sent. 1st and 2nd list doesn't send anything.
I realize that my problem is my codes only sent data from the last drop-down list, not both. I only need 1 data from either drop-down list, but I need both to function. If I can only choose one list, I dont even need to make 2 drop-down list.
This is my codes, but not a full code. The other data works fine, only the drop-down list is having problem.
<form name="list" action="index.php?site=11" method="post">
<script>
function check(){
if(document.getElementById('1H').checked) {
document.getElementById('D1H').style.display = 'block';
document.getElementById('D2H').style.display = 'none';
}
else {
document.getElementById('D1H').style.display = 'none';
document.getElementById('D2H').style.display = 'block';
}}
</script>
Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour
Choose time slot:
<div id="D1H" style="display:none">
<select name="time1" >
<option value="">---Choose---</option>
<option value="8-9">8:00am-9:00am</option>
</select>
</div>
<div id="D2H" style="display:none">
<select name="time2" >
<option value="">---Choose---</option>
<option value="8-10">8:00am-10:00am</option>
</select>
</div>
<input type="submit" name="submit" value="Next">
This is php codes to show how I receive the POST data, just until the query.
include('../include/dbconnect.php');
$user = $_SESSION['username'];
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time'];
echo "1:".$time;
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
if(isset($_POST['time2'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time2'];
echo "2:".$time;
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
}
echo "3:".$time;
How do I solve this problem? I need to make sure that both drop-down list can sent POST data to another pages, not only one functioning at all. I hope you can understand my problem.
EDIT: I have change both select box's names.
2nd EDIT: I add Fred's code
The select boxes both have the same name. You need to set different name attributes for the two select options.
Edit
The issue is that the select box will post data even if it's not explicitly set. So each isset() will always return true.
As long as your default option has an empty value attribute you can check against that like this:
if(!empty($_POST['time']))
Or maybe set a default value to test against like so:
<option value="0">---Choose---</option>
<?php if($_POST['time'] != '0') ?>
The original issue was that the form would always post the last select even if you only made a choice with the first one. The issue now is that both if(isset clauses will be true.
What has already been said in regards to both selects holding the same name, still stands.
Sidenote: (I renamed the 2nd select to time2)
However, in order to use the time from either radio button/dropdown selects, you need to use an isset conditional statement, then use that variable for your DB insert.
Tested as follows while naming the submit button as my own self test and inside the same file. You can modify it to suit.
Scenario: The $time variable that's being (set) then passed to your DB, will be set as such, depending on which time select was chosen.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$time=$_POST['time'];
echo $time;
}
if(isset($_POST['time2'])){
$time=$_POST['time2'];
echo $time;
}
}
?>
<form name="list" action="" method="post">
<script>
function check(){
if(document.getElementById('1H').checked) {
document.getElementById('D1H').style.display = 'block';
document.getElementById('D2H').style.display = 'none';
}
else {
document.getElementById('D1H').style.display = 'none';
document.getElementById('D2H').style.display = 'block';
}}
</script>
Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour
Choose time slot:
<div id="D1H" style="display:none">
<select name="time" >
<option value="">---Choose---</option>
<option value="8-9">8:00am-9:00am</option>
</select>
</div>
<div id="D2H" style="display:none">
<select name="time2" >
<option value="">---Choose---</option>
<option value="8-10">8:00am-10:00am</option>
</select>
</div>
<input type="submit" name="submit" value="Next">
EDIT (DB-related)
And in your case, it would be: (and do name your submit button to name="submit" for this):
<?php
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time'];
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
if(isset($_POST['time2'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time2'];
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
}
?>
Related
Okay My problem is little complex which I am unable to solve. I already have two select boxes in which the options are coming from Database Mysql through php. Like when I select an option in Select Box#1, Select Box#2 gets updated through ajax and displays the options against SelectBox#1 from MYSQL Database. I am able to store the values from those two in database as well.
Problem
:
Now the problem is that I want a button like "Add New" that should create same two select boxes with same functionality the number of times i click Add New Button. Example: I filled the original two select boxes, then I click Add New and two new select boxes gets generated.. I fill them and again click Add New and two more select boxes gets generated so total of 6 select boxes with same first Select Box options but options in Second Select Box may differ according to the option selected in first select box. Now, two things I need help in:-
1. How to perform this Add New button thing that generates select boxes with same functionality as the original ones i.e Select Option from First Select Box, Second Select Box gets auto updated according to the option selected in first select box and the options are fetched from Database.
2. How do I read and store those values selected from new fields? I am able to read and store values that were passed from the original two select boxes but how about the new ones? Any unique names or ids of new select boxes I generate through button or some sort of array etc?
Here is my code that I used for my first two select boxes:-
HTML FILE-TOP
function load_country()
{
$connection = new mysqli("localhost","root","","test");
$query = "SELECT * FROM country";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["c_id"].'">'.$row["c_name"].'</option>' ;
}
return $output;
}
HTML FILE-INSIDE
<form method="post">
<p> <select name="country" id="country">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select> </p>
<p> <select name="city" id="city">
<option value="">Select City</option>
</select> </p>
<input type="submit" name="submit" value="submit">
</form>
Jquery/Ajax Function that updates the Second Select Option:-
$(document).ready(function(){
$('#country').change(function(){
var country_id = $(this).val();
$.ajax({
url:"fetch_city.php",
method:"POST",
data:{
"c_id":country_id
},
dataType: "text",
success:function(data)
{
$('#city').html(data);
}
});
});
});
</script>
PHP File used by Ajax to Update Second Select Box:-
$output = '';
$query = "SELECT * FROM cities WHERE country_id = '{$_POST["c_id"]}'";
$result = mysqli_query($connection,$query);
$output = '<option value="">Select City</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["city_id"].'">'.$row["city_name"].'</option>' ;
}
echo $output;
First Change the HTML into something like this, use classes and ids for finding objects better:
<form method="post">
<div id="form-area">
<div class="select-box" id="box_1">
<p>
<select class="country" name="country[]">
<option value="">Select Country</option>
<?php echo load_country() ?>
</select>
</p>
<p>
<select class="city" name="city[]">
<option value="">Select City</option>
</select>
</p>
</div>
</div>
<button id="add_new" type="button"> [+] </button>
<input type="submit" name="submit" value="submit">
</form>
javascript:
$(document).on("change", ".country", function() {
var current_box = $(this).parent().closest('div').attr('id');
var country_id = $(this).val();
$.ajax({
url: "fetch_city.php",
method: "POST",
data: {
"c_id": country_id
},
dataType: "text",
success: function(data) {
$('#' + current_box).find(".city").html(data);
}
});
});
var id = 1;
$('#add_new').click(function() {
id++;
$(".select-box:last").clone().attr("id", "box_" + id).appendTo("#form-area");
});
After that, you should handle Array input in PHP form destination code.
In your case it should be something like this:
$cities = $_REQUEST['city'];
$cuontries = $_REQUEST['cuontry'];
foreach( $cuontries as $key => $cuontry ) {
$row[] = [ "cuontry" => $cuontry , "city" => $cities[$key] ];
}
This array is as same as form array that you created with [+] button in HTML
OK, So not a big HTML or Javascript person. But I am doing what I can to get by.
I am working on a project for a Marine Cadets Explorers Post to create a online database for them to help manage their membership and other functions. In entering their membership records they will have multiple families that will have several kids in the post, so they don't want to have to re-enter their parents records. I wanted to create a drop down box that is populated by a SQL Database lookup (Which I did) and then, if they select a parent from that list, the form will populate, saving the entry.
I only provided a snipped of the HTML, since the form has over 50 fields and for example, I only really need to show one.
So the HTML is below.
<form name="YouthApp" class="form-application" method="post" id="application-form">
<div style="height:0.20in; left:1.75in; overflow:hidden; padding:2px; position:absolute; top:4.10in; width:1.48in; ">
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<?php makeSuppDropdown() ?>
</select>
<div style="height:26px; left:0.36in; overflow:hidden; padding:2px; position:absolute; top:4.52in; width:353px; ">
<input style="height:0.20in; width:3.64in; " name="SuppFirst" required value="<?php if(isset($_POST['SuppFirst'])){ echo $_POST['SuppFirst']; } ?>" maxlength="20" type="text" placeholder="First Name" >
</div>
</div>
</form>
It calls a PHP Function that populates the drop down:
function makeSuppDropdown() {
include("dbconnect.php");
$sql = "SELECT SupporterId, ".
"CONCAT(LastName, ',', FirstName,' ',MidName,' ',trim(Suffix)) as 'SuppLookup' ".
"FROM tblsupporters ".
"ORDER BY LastName, FirstName, MidName, Suffix";
$sql_result = mysqli_query($conn,$sql);
$field= mysqli_fetch_fields($sql_result);
while ($row = mysqli_fetch_array($sql_result)) {
echo ' <option value="'.$row['SupporterId'].'" >'.$row['SuppLookup'].'</option>'.chr(10);
}
}
The function provided the following output:
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<option value="32517-02" >Truxton,Karla Andrianne </option>
<option value="32517-01" >Truxton,Tommie Lee </option>
</select>
If the user selects a Parent Supporter then I wanted to start filling in the input fields. This is where I am having a problem.
Here is the PHP/Javacode I am using that is not working:
<?php
if (isset($_POST['selSupp'])) {
?>
<script type="text/javascript">
document.getElementById("SuppFirst").value = "Tommie";
</script>
<?php
} ?>
Now I know that PHP and Javascript don't always play well together, but I'm hoping that there is a solution that will allow me to fill in the fields.
Thank you in advance.
I don't really understand your question, however, to the best of my knowledge, you want the users after choosing their parents' information, a form appears with filled parents' info and extra fields.
If so, i suggest creating a submit button, since I'm not sure if a drop-down select can be submitted on itself:
if ($_POST['sbm']) { //if submit button is pressed
$option = mysqli_real_escape_string($conn, $_POST['select-name']);
//Get option from the users
if ($option == '') { //If $option == '' means if there is no value
header("Location: this_file.php?error=notselected"); //Redirect to the desired page
exit();
}
else {
header("Location: this_file.php?error=noerror");
exit();
}
}
And in the desired page (the page that contains the select form), you add:
if (isset($_GET['error'] && !empty($_GET['error'])) { //Check if error parameter exists
$error = $_GET['error'];
//Get the error
switch ($error) {
case "notselected": echo "<b style=\"color:red;\">Error!</b>"; break;
case "noerror": echo "<script>$(document).ready(function(){$('input-wanted-to-show').show();});</script>"; break; //Print out the script part that you need or show the hidden input. After this php code, please go to html and add desired input fields.
}
}
Overall, I know you want to submit that select form and add javascript if it is done, so I advice is to add a submit button, add parameter when option is valid, then use $_GET to check the parameter, print out the approriate tags.
If you still want to keep the select value, use AJAX.
If there is any problem, just comment.
I will be glad to help you figure out!
I am running into a roadblock when attempting to use JavaScript to update a <select> tag on a page that I am creating. The issue I have is that this is a management style page, so there are multiple forms on one page, each one generated through PHP for an entry in a SQL database. For a better understanding of what I am talking about, here is some code from my project:
<?php
$query = "SELECT * FROM tableA ";
$data = $PDOcon->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$head = $row['head'];
$cont = $row['content'];
$app = $row['Product'];
$category = $row['CatID'];
Print "<form class='mgmt-ListView-Tall' action=\"#Anchor$id\" method=\"post\" width=\"60%\">
<input type=\"hidden\" name=\"id\" value=\"$id\" readonly />
<label for='pHead'>Heading: </label>
<input id='pHead' class='lbl-w25' name='pHead' value='$head' />
<label for='pCont'>Content: </label>
<input id='pCont' class='lbl-w20' name='pCont' value='$cont' />
<label for='pProd' >Product: </label>
<select id='pProd' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp'>Application: </label>
<select id='pApp' name='pApp' class='pApp'>
</select>
</select>
<span><input class='mgmt-Button' id='editbtn' type=\"submit\" name='edit' value='Edit' /></span>
</form>";
}
?>
<script type="text/javascript">
$('.pProd').change(function(){
var string = this.value + ',' + '-1';
$.ajax({
url: 'scripts/get_app.php',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp').innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
});
});
</script>
I have a table (TableB) that contains a list of all applications linked with their product, and what I am attempting to do currently is set up the page so that if the user changes the product in the select field on one of the forms that is generated, the application select tag is updated through AJAX. I am able to get it to update the first form on the page using document.getElementById, but I need it to update the tag with that id that is in the same form as the select tag the user was modifying (example: user makes a change to the pProd tag in the 4th form, the pApp tag in the 4th form gets updated)
I have attempted to call $(this).next(".pApp").innerHTML=data;, but this does not appear to find the tag with the correct class. I have also tried using closest() and sibling() to no avail. I have also tried referencing both id, and class with the same results, and I have searched around and could not find any solution to a problem similar to this. Does anyone have any suggestions?
The id attribute needs to be unique:
The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).1
So one solution is to append $id to the id attributes of the select lists.
<label for='pProd$id' >Product: </label>
<select id='pProd$id' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp$id'>Application: </label>
<select id='pApp$id' name='pApp' class='pApp'>
Then in the AJAX updater, parse out that value for $id using String.replace():
$('.pProd').change(function(){
var id = this.id.replace('pProd','');
var string = this.value + ',' + '-1';
$.ajax({
url: '<?php echo $_SERVER['PHP_SELF'];?>',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp'+id).innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
See it demonstrated in this phpfiddle.
Additionally, since jQuery is being used, the id selector and html() could be used to update the second select list:
success:function(data){
$('#pApp'+id).html(data);
}
1https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
Please help me.. i have dropdownlist which i have populated from the database table, now i want to fill textbox from the database list...
i have one table
id | juice | rupees
now when i select Mango Juice from juice column from dropdownlist it should show the cost of Mango Juice in textbox by retrieving from rupees column
here is the dropdownlist which is populated from the table
<select name="drink" id="drinkid">
<option id="0">-- Select the drink --</option>
<?php
require("dbcon.php");
$getalldrinks = mysql_query("SELECT * FROM tableone");
while($viewalldrinks = mysql_fetch_array($getalldrinks)){
?>
<option id="<?php echo $viewalldrinks['id']; ?>"><?php echo $viewalldrinks['juice'] ?></option>
<?php
}
?>
</select>
and here is the textbox
<input type="text" name="juicename" id="juiceid" placeholder="Juice">
Please help me.. thanks in advance.
First add onChange() event to your select tag to call function fillTextBox() every time you change option, then the function will fill the textbox:
<select name="drink" id="drinkid" onChange="fillTextBox()">
Now you have to get rupees column & store it in every option using data attribute :
<option data-rupees="<?php echo $viewalldrinks['rupees']; ?>" id="<?php echo $viewalldrinks['id']; ?>" ><?php echo $viewalldrinks['juice'] ?></option>
Create the function fillTextBox() that will fill the textbox by rupees value of selected option :
function fillTextBox(){
var myselect = document.getElementById("drinkid");
var rupees = myselect.options[myselect.selectedIndex].getAttribute("data-rupees");
document.getElementById("juiceid").value = rupees;
}
That should do the work, hope this helps.
You'll need to use javascript to detect changes in your select box, store those values, and then populate the text box with the desired values. You haven't listed a text box in your html, so I'll have to assume that I can access this value using input[type=text]. Here's an approximation of what your javascript should look like given that I am working with incomplete information. Note that your should probably contain an attribute called value to store your id instead of using the id attribute.
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.querySelectorAll('input[type=text]')[0].value = data.text;
});
You'll need to provide more detail and more of your code if you want an exact solution to your problem.
UPDATE: I see you've added the text box HTML, so here's the updated version of the event handler:
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.getElementById('juiceId').value = data.text;
});
I have two dropdown lists, the first is populated from database and works fine, the second dropdown must be populated dynamically from what user has chosen from the first dropdown list. For example, my first dropdown contains many country's name, when user choose a country, the second dropdown will be populated by city's of that country which are in same database. Have anyone an example of this?
This is the first dropdown list
<select size="1" name="listeOrg">
<option value = "0" selected>---Choisir une région---</option>
<?php
$link3 = mysql_connect_db();
$query3 = "SELECT nom_region FROM region ";
$result3 = mysql_query($query3, $link3) or die();
while ($row = mysql_fetch_array($result3)) {
echo '<option value="'.$row['nom_region'].'">'.$row['nom_region'].'</option>';
}
mysql_close($link3); ?>
</select>
And the second:
<?php
$link4 = mysql_connect_db();
$selectregion=$_POST['listeOrg'];
$query4 = "SELECT organisme FROM region_organisme where nom_region='$selectregion' ";
$result4 = mysql_query($query4, $link4) or die();
while ($row2 = mysql_fetch_array($result4)) {
echo '<option value="'.$row2['nom_region'].'">'.$row2['nom_region'].'</option>';
}
mysql_close($link4); ?>
<option value="1" >autre
</select>
I found finally a good solution with a proper code. This is the link to the tutorial if someone has been stacked on this case.
A good explained tutorial with demo