change select box value using other select box - php

I am working on an administrative form where I have to select the client first and then select the building.
I have in the database a table with clients and another with the buildings of the clients correctly associated.
The problem is that I I wanted to do a select with the clients and a select with the buildings but instead of showing all the buildings, only showing the ones of the selected client.
I was able to do the code below after a lot of research, but I could not get it to fetch the values to bd to the salect of the building.
This form is for managers to assign tasks to technicians, where technicians will have to do pre-contracted services.
<!DOCTYPE html>
<html>
<head>
<script>
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
} else if(s1.value == "Dodge"){
var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />
</body>
</html>
as a final result would have to be for example if I select the client AAA must appear in buildings only the buildings associated with the customer AAA:
AAA-buildings1
AAA-buildings2
AAA-buildings3
...

If I understand the question, you wish to (a) trap the user's SELECT choice of client, and then use that information to get the appropriate info from the database in order to populate the second SELECT.
This is exactly the type of scenario for which AJAX was created. It's actually pretty simple (more simple with jQuery than with pure js, but isn't everything...). Here are some examples on how it works:
dropdown options is dependent from another dropdown options (all value from database)
A basic video tutorial re ajax (pure javascript)
Code Examples:
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="slct1" name="slct1">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
JS/JQuery:
$('#slct1').change(function(){
let s1 = this.value;
$.ajax({
type: 'post',
url: 'myajax.php',
data: 's1=' + s1
}).done(function(d){
$('#slct2').html(d); //"d" can be any varname you want (here AND line above)
});
});
PHP file: (myajax.php)
<?php
$sel1 = $_POST['s1'];
if ($sel1 == 'Chevy'){
$out = '<option value="Cobalt">Cobalt</option>';
$out += '<option value="Camaro">Camaro</option>';
$out += '<option value="Malibu">Malibu</option>';
$out += '<option value="Silverado">Silverado</option>';
}elseif ($sel1 == 'Ford'){
$out = '<option value="Model A">Model A</option>';
$out += '<option value="F150">F150</option>';
$out += '<option value="Mustang">Mustang</option>';
$out += '<option value="Mondeo">Mondeo</option>';
}
echo $out;
Example 2:
Untested and off-the-cuff, but you get the idea
<?php
include 'connect.php'; //connects to MySQL and creates $conn
$sel1 = $_POST['s1'];
$query = "SELECT * FROM `cars` WHERE `brand`='" .$sel1. "' ";
$aR = mysqli_query($conn, $query);
$out = '';
while ($r = mysql_fetch_assoc($aR)){
$out .= '<option value="' .$r['model']. '">' .$r['model']. '</option>';
}
echo $out;

Related

How to get the text option of MySql select?

I'm pretty new to Php and web development. What I'm trying to do here is besides fetching the value of selected id pck which is rate_perhour, I also want to fetch the value of option pack_id to POST on an insert file.
<?php
include ("dbconn.php");
$data = mysqli_query($db,"SELECT * FROM packages");
$cek = mysqli_num_rows($data);
$select= '<select id="pck" name="pck" class="form-control">';
$select.='<option value="">-- Select Package --</option>';
while($rs=mysqli_fetch_array($data,MYSQLI_ASSOC))
{
$select.='<option value="'.$rs['rate_perhour'].'">'.$rs['pack_id'].'</option>';
}
$select.='</select>';
echo '<input type="hidden" name="packid" id="packid">';
echo "<span class=style7>".$select."</span>";
?>
I'd tried the script to pass value into the hidden input to hold the id but didn't work as well.
<script>
$(document).ready(function()
{
$("#pck").change(function()
{
$("#packid").val(("#pck").find(":selected").text());
});
});
</script>
Parts of the POST method. It can get the Selected Value(pck) but not Option(packid)
<php
include ("dbconn.php");
if(isset($_POST['cuid']))
{
//Insert into 'reservation' table
$pack =$_POST['packid']; // Option
$rate =$_POST['pck']; // Selected Value
}
else
{
} ?>

Delete Blank option Jquery and PHP

I need to remove the blank option.
This is a restaurant web page and this is the reservation form.
The thing is that they are reciving a lot of "blank" reservation hours because people don't specify the reservation hour.
Sorry for my English, I'm from Spain :)
The code:
HTML read by browser
<div id="lashoras">
<select name="Hora" size="1" onChange="updateHoraPersonas();">
<option value="" selected="selected"> </option>
<option value="1330">13:30</option>
<option value="1400">14:00</option>
<option value="1430">14:30</option>
<option value="1500">15:00</option>
<option value="1930">19:30</option>
<option value="2000">20:00</option>
<option value="2030">20:30</option>
<option value="2100">21:00</option>
<option value="2130">21:30</option><option value="2200">22:00</option></select>
</div>
source code HTML
<div id="lashoras">
<?php
echo $selectFullDay;
?>
SelectFullDay PHP Var
$selectFullDay = build_select_options ("Hora","id_lookup","lookup","lookups",0," ",$onChange,$theWhere,$multiple,$orderby);
updateHoraPersonas Function
function updateHoraPersonas(){
var mediodiaMax = maxPersonas;
var nocheMax = maxPersonas;
mediodiaMax = maxPersonas-curDia_mediodia_reservados;
if(mediodiaMax<0) mediodiaMax = 0;
nocheMax = maxPersonas-curDia_noche_reservados;
if(nocheMax<0) nocheMax = 0;
var hora = $('#lashoras').val();
//hora blank for first, otherwise 1330
//primero ver si llegado a tope de mediodia/noche
if (hora <= horaCambio) {
selectMax = mediodiaMax;
} else {
selectMax = nocheMax;
}
//y ahora hora a hora
selectMax = Math.min(selectMax,horasArray[hora]);
var Numero_de_personasSelect = "";
for (i=1 ; i<= selectMax ; i++) {
if (i==1) {
selected = "selected='selected'";
} else {
selected = "";
}
Numero_de_personasSelect += "<option value='"+i+"' "+selected+" >"+i+"</option>";
}
if (selectMax <=0 ) {
Numero_de_personasSelect += "<option value=''>Completo</option>";
}
$("#Numero_de_personas").html(Numero_de_personasSelect);
//alert('mediodiaMax: '+mediodiaMax+' | nocheMax: '+nocheMax+' | selectMax: '+selectMax);}
</script>
....
Change the form submission so that the user cannot submit if the reservation time is not specified! This way you processing time does not increase on explicitly removing blank options
an exapmle
<?php
if(!isset($_POST['time'])){
//'Enter valid details
}else{
//redirect here
}

Interactive Form depending on Select List not working

So I am trying to make this clip submission form interactive in the following way:
I want the second Select list choices to change according to which city is selected in the first select list.
Here is my script function code:
<script>
function spotListChange(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == ""){
var optionArray = ["|"];
}
<?php
while ($cityList = $cityListDB->fetch()) {
$city = $cityList['city'];
$spotList = $db->query("SELECT * FROM spots WHERE city='$city' ORDER BY name");
?>
else if(s1.value == "<?php echo $city; ?>"){
var optionArray = ["|"
<?php
while ($spot = $spotList->fetch()) {
echo ", \"" . $spot['city'] . "|" . $spot['city'] . "\"";
}
?>
];
}
<?php
}
?>
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
Here is the part of the form with the two select lists. (I'll get rid of most city options available just to make the code shorter)
<select id="city" name="city" style="margin-left: 135px;" onChange="spotListChange('city', 'spotSelectList')" required>
<option value="" selected="selected">Ville...</option>
<option value="Albanel">Albanel</option>
<option value="Alma">Alma</option>
<option value="La Doré">La Doré</option>
<option value="Saint-Félicien">Saint-Félicien</option>
<option value="Mashteuiatsh">Mashteuiatsh</option>
</select><br />
<select id="spotSelectList" name="spot" style="margin-left: 135px;">
</select>
If I change the PHP inside the else if by fix/text values, it works fine, so the issue must be there, but I don't get where the issue is.
Do yourself a favor and use jquery for it, it makes your code more simple and is a plenty of tutorial out there.
I recomend you make a json response from php to an ajax call from jquery (javascript).
Can you see this as reference:http://simpleweb.github.io/jquery-dependent-selects/
also this:http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
Hope this helps you.

code igniter - form dropdown selecting correct value from database (state & city using javascript)

I have a similar problem like this one: Code Igniter - form_dropdown selecting correct value from the database, but in this case, i have 2 dropdown, State & City (using JavaScript). The dropdown option for City is repopulated based on what user choose in State dropdown.
For example, when a user choose a State (eg: New York), then the dropdown options for City become only cities in New York (eg: Albany, Amsterdam etc).
After user selects a value, then hits save, its saved to the database.
The problem is, how do i get the dropdown to automatically choose the one thats been selected by the user in the initial stage? I can do it if it's only 1 dropdown option. But in this case, the dropdown for City is repopulated based on what user choosed in State dropdown option.
Controller:
//this one i managed to get it automatically choose the one that's been selected by the user in the initial stage
$username=$this->session->userdata('username');
$data['orgtype'] = $this->m_user->get_orgtype_dropdown($username);
//these two are the problem
$data['state'] = $this->m_user->get_state_dropdown($username);
$data['city'] = $this->m_user->get_city_dropdown($username);
Model:
function get_orgtype_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['orgtype']] = $row['orgtype'];
}
return $return;
}
function get_state_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['state']] = $row['state'];
}
return $return;
}
function get_city_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['city']] = $row['city'];
}
return $return;
}
View:
<?php
$orgtypeOption = array(
'Academic' => 'Academic',
'Professional' => 'Professional',
);
echo form_label("Organization Type : ");
echo form_dropdown('orgtype', $orgtypeOption, $orgtype);
echo br();
echo form_label("State : ");
?>
<select name ="state" id="countrySelect" size="1" onChange="makeSubmenu(this.value)">
<option></option>
<option value="USA" <?php if ($state=="USA") echo 'selected="selected"';?>>USA</option>
<option value="Singapore" <?php if ($state=="Singapore") echo 'selected="selected"';?>>Singapore</option>
<option value="Jawa Timur" <?php if ($state=="Jawa Timur") echo 'selected="selected"';?>>Jawa Timur</option>
<option value="Jawa Barat" <?php if ($state=="Jawa Barat") echo 'selected="selected"';?>>Jawa Barat</option>
</select>
<?php
echo br();
echo form_label("City : ");
?>
<select name="city" id="citySelect" size="1">
<option></option>
</select>
JavaScript:
var citiesByState = {
USA: ["NY","NJ"],
Singapore: ["taas","naas"],
"Jawa Timur": ["Surabaya","Malang"],
"Jawa Barat": ["Bandung","Banjar"]
};
function makeSubmenu(value) {
if(value.length==0) document.getElementById("citySelect").innerHTML = "<option></option>";
else {
var citiesOptions = "";
for(cityId in citiesByState[value]) {
citiesOptions+="<option>"+citiesByState[value][cityId]+"</option>";
}
document.getElementById("citySelect").innerHTML = citiesOptions;
}
}
function displaySelected() {
var country = document.getElementById("countrySelect").value;
var city = document.getElementById("citySelect").value;
alert(country+"\n"+city);
}
function resetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").selectedIndex = 0;
}
Here's the preview: application preview picture
Help please

How to keep selected value in a dropdown box using JQUERY?

Hi am using a jquery code like this
$(".selfont").change(function(event){
$('#dav').val();
window.location ='?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val() ;
});
I want to keep the dropdown value selected by the user in each dropdown boxes. But at present the value is not the one selected by the user, its always showing the first value. How can I set the dropdown field with value selected by the user using jquery? Please help me.
My first select box code is like below
<select name="dav" id="dav" style="width: 275px" class='selfont' >
<option value='' class=''>Select one</option>
<?php
$test = mysql_query("SELECT DISTINCT DataVersion FROM olivesdeptable ORDER BY DataVersion DESC");
$i=1;
while($numval=mysql_fetch_array($test))
{
print "<option value=\"".$numval['DataVersion']."\">".$numval['DataVersion']."</option>";
$i=$i+1;
}
?>
</select>
Even if we select value it will show as "Select one" in the field.
javascript code for dropdown fields
<script type="text/javascript">
if (document.getElementById("dav").selectedIndex < 1)
{
document.getElementById('pathogen').selectedIndex = "";
document.getElementById('pathogen').disabled = true;
}
if (document.getElementById("pathogen").selectedIndex < 1)
{
document.getElementById('topicF').selectedIndex = "";
document.getElementById('topicF').disabled = true;
}
if (document.getElementById("topicF").selectedIndex < 1)
{
document.getElementById('ind').selectedIndex = "";
document.getElementById('ind').disabled = true;
}
if (document.getElementById("ind").selectedIndex < 1)
{
document.getElementById('subind').selectedIndex = "";
document.getElementById('subind').disabled = true;
}
if (document.getElementById("subind").selectedIndex < 1)
{
document.getElementById('countryR').selectedIndex = "";
document.getElementById('countryRF').options.length = 0;
document.getElementById('countryRF').selectedIndex = "";
document.getElementById('countryR').disabled = true;
document.getElementById('countryRF').disabled = true;
}
</script>
even the value is updated, the second drop down box is showing as disabled ?
Next dropdown field markup is as below
<select name="pathogen" id="pathogen" style="width: 275px" class='selfont' >
<option value=''>Select one</option>
<?php
$test = mysql_query("SELECT DISTINCT Pathogen FROM olivesdeptable where DataVersion='$davQ' ORDER BY Pathogen ASC");
$i=1;
while($numval=mysql_fetch_array($test))
{
print "<option value=\"".$numval['Pathogen']."\">".$numval['Pathogen']."</option>";
$i=$i+1;
}
?>
</select>
only first dropbox value is working for next dropbox value is storing in url but in page the value shows as 'Select one' ? Please help to sort
$(document).ready(function () {
$('#dav').val(getURLParameter('davQ'));
$('#pathogenQ').val(getURLParameter('pathogenQ'));
$('#topicQ').val(getURLParameter('topicQ'));
$(".selfont").change(function (event) {
window.location = '?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val();
});
function getURLParameter(name) {
return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
});
<?php
$test = mysql_query("SELECT DISTINCT DataVersion FROM olivesdeptable ORDER BY DataVersion DESC");
$i=1;
$selected = '';
// make compare with the value you want to select with the parameter form url
// here I assume $_GET['davQ'] holds the value to $numval['DataVersion']
if($_GET['davQ'] == $numval['DataVersion']) $selected = 'selected';
while($numval=mysql_fetch_array($test))
{
echo "<option value=\"".$numval['DataVersion']."\" $selected>".$numval['DataVersion']."</option>";
$i=$i+1;
}
?>

Categories