I have a SELECT input that gets all of its options via the database. Below the select input, there are divs created for each option in the select. I want the user to select an option from the drop down and make the div below display. So basically the drop down are sports, and if they make a selection the sport div hidden below will load, and that div will contain all the sport positions
<select name="sport" id="select">
<?
foreach ($getSports as $row) {
echo '<option onClick="toggle'.$row['1'].'()" onLoad="toggle'.$row['1'].'()" value="' . $row['0'] . '">' . $row['1'] . '</option>';
}
?>
</select>
</label>
<?
foreach ($getSports as $row) {
echo '<div id="position' . $row['1'].'" style="margin-top: 5px;display:none;">Positions:' . $row['1'].'';
$sport = $row['0'];
$getPositions = $model->getPositions($sport);
foreach ($getPositions as $row2) {
echo '<label style="float:right">'.$row2['1'].'</label>';
echo '<input type="checkbox" name="'.$row2['1'].'" value="'.$row2['0'].'">';
}
echo '</div>';
}
?>
How about modifying your code like this? Seems to be more semantic:
<select name="sport" id="select">
<? foreach ($getSports as $row) {
echo '<option data-row-id="'.$row['1'].'" value="'.$row['0'].'">'.$row['1'].'</option>';
} ?>
</select>
</label>
<? foreach ($getSports as $row) {
echo '<div data-position="'.$row['1'].'" style="margin-top:5px;display:none;">Positions:' . $row['1'].'';
$sport = $row['0'];
$getPositions = $model->getPositions($sport);
foreach ($getPositions as $row2) {
echo '<label style="float:right">'.$row2['1'].'</label>';
echo '<input type="checkbox" name="'.$row2['1'].'" value="'.$row2['0'].'">';
}
echo '</div>';
}?>
<script>
$(function() {//create the binding once the document is ready
$('#select').change(function() {
var select = $(this);
var selectedOption = select.find(':selected');
var position = selectedOption.attr('data-row-id');
var divContext = $('[data-position="'+position+'"]');
$('[data-position]').not(divContext).hide();
divContext.show();
});
});
</script>
If you want to keep visible only the selected sport, I suggest this.
(1) add a class to the div which holds sports information - ex. class="sportsHolder"
(2) change this part
onClick="toggle'.$row['1'].'()" onLoad="toggle'.$row['1'].'()"
to
onClick="toggle('.$row['1'].');" onLoad="toggle('.$row['1'].');"
(3) create the function
<script type="text/javascript">
function toggle(whichPos) {
$(".sportsHolder").hide();
$("#position" + whichPos).show();
}
</script>
at least I would do it that way.
Related
Im trying to use PHP+MySQL+Ajax to dynamically load options in a select but I don't know how to do it
Currently I have 2 select inside 2 forms and i need to send form 2 times, so the page will load 2 times.
I want to improve my code using ajax, so my page will load faster and will be easier to use.
Select 1 have a list of countries
Select 2 have a list of cities from the country selected in select 1
After you select the city, specific info from that city will be displayed in screen.
Form 1
<?php include_once "conn.php"; ?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
Form 2
<!-- Store select 1 value in variable -->
<?php
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
}
?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Cities" name="Cities">
<?php
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="ShowInfo" name="ShowInfo" value="ShowInfo" />
</form>
Display City info on screen:
<!-- Store select 2 value in variable and print selected options in screen-->
<?php
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<p>Country: ' . $row["Country"] . '</p>';
echo '<p>City: ' . $row["City"] . '</p>';
}
} else {
echo "0 results";
}
}
?>
For Ajax to work without you refreshing or submitting the forms. You need to create separate endpoints for your ajax calls. You should have 3 files:
index.php - Display the country form, city form and city info altogether here. The country data will load by default and other data will be linked to their respective Ajax calls.
fetchCities.php - Use this endpoint to fetch the dropdown values of cities based on the selected country value.
cityInfo.php - Use this endpoint to fetch the city information based on the selected city value.
Note: You can combine fetchCities.php and cityInfo.php into a single file if you include a second parameter in your Ajax call, for eg: action: "fetchCity"
Here's what you can do:
index.php
<?php include_once "conn.php"; ?>
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
//empty city dropdown. You may remove the form element from it if not required.
<form action="" method="post">
<select required id="Cities" name="Cities">
<option disabled selected>Select a country first</option>
</select>
</form>
//empty city info
<div id="cityInfo"></div>
<script>
//whenever someone selects a country, hit the Ajax to fetch cities.
$(document).on('change', '#Countries', function() {
const selectedCountry = $(this).val();
//run your cities Ajax here and pass selectedCountry value
$.ajax({
method: "POST",
url: "fetchCities.php",
data: {
Countries: selectedCountry
}
})
.done(function(response) {
//replace City dropdown with values returned from fetchCities.php file.
$('#Cities').html(response);
});
});
//whenever someone selects a city, hit the Ajax to fetch city information.
$(document).on('change', '#Cities', function() {
const selectedCity = $(this).val();
//run your cities Ajax here and pass selectedCity value
$.ajax({
method: "POST",
url: "cityInfo.php",
data: {
Cities: selectedCity
}
})
.done(function(response) {
$('#cityInfo').html(response);
});
});
</script>
fetchCities.php
<?php include_once "conn.php";
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
$returnHtml = '<option disabled selected>0 results</option>';
}
echo $returnHtml;
}else{
echo '<option disabled selected>0 results</option>';
}
?>
cityInfo.php
<?php
include_once "conn.php";
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<p>Country: ' . $row["Country"] . '</p>';
$returnHtml .= '<p>City: ' . $row["City"] . '</p>';
}
echo $returnHtml;
} else {
echo "0 results";
}
}else{
echo "0 results";
}
?>
Also, as Dharman mentioned, you should really use parameterized queries. I know that seems like some extra work but trust me, it will be worth your time.
(Too long for a Comment.)
Let me get this straight. On a single page:
The page is initialized with a list of all countries. (Either when building the page, or via AJAX.)
The user selects one country from a list of all the countries.
A second database lookup finds the cities in that country.
Then something is done with those cities.
That must be two lookups.
Since you mentioned AJAX, you want to do all this without reloading the page? Be aware that <form> wants to reload the page. Yes you can pervert to do AJAX, but why have <form> if you won't be submitting and reloading the page?
The complete list of cities in the world is over 3 million. Are you working with that sized table? Or some subset, such as "cities that have a Burger King in it"?
I have code like this which I executed from backend :
$statement = $PDO->prepare($query);
$statement->execute($parameters);
if($statement->rowCount()>0)
{
$resultSet = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $key => $value)
{
$return .= "<option value='".$resultSet[$key]['bwid']."'>".$resultSet[$key]['bname']." - ".$resultSet[$key]['final_count']."</option>";
}
}
else
{
$return = "<option>$lbldisp_text_nosuppfound</option>";
}
echo json_encode($return);
How do I put a label that says "choose branch" (i want it as the first option) ?
Thank you.
Just add a label tag and write your label text inside it.
$return .= "<label>choose branch</label>";
$return .= "<option value='".$resultSet[$key]['bwid']."'>".$resultSet[$key]['bname']." - ".$resultSet[$key]['final_count']."</option>";
Simply append your label to the $return variable
$return .= '<label>Write text here</label>';
$return .= "<option value='".$resultSet[$key]['bwid']."'>".$resultSet[$key]['bname']." - ".$resultSet[$key]['final_count']."</option>";
echo $return;
First, you have to add a element surrounding the options to have a valid html document.
Then you can add a disabled option in your select
if($statement->rowCount()>0){
$resultSet = $statement->fetchAll(PDO::FETCH_ASSOC);
$result = '<label>Choose your branch</label><select>'; //open the select and add the label
$result .= '<option selected disabled>Choose branch</option>'; // add a disabled option with label
foreach ($resultSet as $key => $value) {
$return .= "<option value='".$resultSet[$key]['bwid']."'>".$resultSet[$key]['bname']." - ".$resultSet[$key]['final_count']."</option>";
}
$result .= '</select>'; // close the select
} else {
$return = "<option>$lbldisp_text_nosuppfound</option>";
}
From what I understand you want to add a label "choose branch" to your select as the first option so it appears in the list not as a <label>. To achieve this you need to add a new option in the list but disable it and set it as selected.
Before you start adding the options to $return with the foreach loop add this line:
$return .= "<option selected disabled>choose branch</option>";
Hello #chrisjai32 try this out
<div id="part">
<label>choose branch</label>
<input type="text" id="" placeholder="Branch Name" autocomplete="off">
<input type="hidden" name="branch_id" id="branch_id">
<div id="branch_options">
<option value="0">--choose branch--</option>
<?php foreach("$branches as $b") { ?>
<option value="<?php echo $b->branch_id; ?>">
<?php echo $c->branch_name; ?>
</option>
<?php } ?>
</div>
</div>
#chrisjai32 this is the script of my above answer
<script>
$(document).ready(function(){
$(document).on("click", "#check_branches", function(e){
branch_id = $("#branch_id").val();
$.ajax({
type: "GET",
url: "<?php echo url('/'); ?>/check_branch/"+brand_id,
success:function(result){
$("#result").html("available " + result);
}
});
return false;
});
});
</script>
I am stuck with small problem.
when i change my drop down list the page is getting reloaded.
Can any one help me .
This code is used to retrieve userid, based on userid get all the application id form drop down and populate it into dropdown list.
If i select value in drop down i am storing selected value
Here is my code.
<?php
$selected = " ";
function get_options($select) {
global $wpdb;
$user_ID = get_current_user_id();
echo $user_ID;
$sql = $wpdb->get_col("select Application_ID from wp3_cteTest where $user_ID = userid");
echo $sql;
//print_r($keysql);
$options = "";
while (list($k, $v) = each($sql)) {
if ($select == $v) {
$options.='<option value="' . $v . '" selected>' . $v . '</option>';
} else {
$options.='<option value="' . $v . '">' . $v . '</option>';
}
}
return $options;
}
if (isset($_POST['applications'])) {
$selected = $_POST['applications'];
echo $selected;
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<?php $default_state = 'please Select your id'; ?>
<select name="applications" onchange=this.form.submit()>
<option value=' ' ><?php echo $default_state ?></option>
<?php echo get_options($selected) ?>
</select>
</form>
</body>
</html>
I Tried removing form, if i remove form drop down doesn't work, I wont get selected value.
Then what is wrong??
Thanks in advance!
You've got onchange=this.form.submit() in your select tag, so when you change the option selected javascript is submitting the form.
Just change...
<select name="applications" onchange=this.form.submit()>
...to...
<select name="applications">
So if you just need the selected id without submit the form then replace this line:
<select name="applications" onchange=this.form.submit()>
with this :
<select name="applications" onchange="getval(this)">
and Add little script :
<script type="text/javascript">
function getval(sel) {
alert(sel.value);
}
</script>
I made a form with some dynamic/concatenated select in this way.
FORM HTML (index.php)
<form id="src_form" action="index.php" method="post">
<p>
<select name="catid_1" id="catid_1" class="fieldmax">
<?php echo $cs->show_cat_1(''); ?>
</select>
</p>
<p>
<select name="catid_2" id="catid_2" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<select name="catid_3" id="catid_3" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<input type="submit" name="submit" value="SRC" id="btn_src">
</p>
</form>
AJAX JS
$(function() {
// Ajax post Page
var urlpage = 'ajax-php/con-select.php';
// Vars
var wait = '<option value="">wait</option>';
var all = '<option value="">all</option>';
// Default
$("select#catid_2").prop("disabled", true);
$("select#catid_3").prop("disabled", true);
// CATID_1 Change
$("select#catid_1").change(function(){
// set var
var catid_1 = $("select#catid_1 option:selected").prop("value");
// laod
$("select#catid_2").html(wait);
$.post(urlpage,
{
catid_1:catid_1
},
function(data){
switch (data) {
case all:
$("select#catid_2").html("");
return false;
default:
$("select#catid_2").prop("disabled", false);
$("select#catid_2").html(data);
return false;
}
});
});
// CATID_2 Change ... etc
});
CON-SELECT.PHP
if(isset($_POST['catid_1']))
{
echo $cs->show_cat_2();
die;
}
if(isset($_POST['catid_2']));
{
echo $cs->show_cat_3();
die;
}
CLASS.PHP
public function show_cat_1()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_1 ORDER BY idcat_1 ASC");
$cat_1 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_1'] . '"';
$cat_1 .= '>' . $row['idcat_1'] . '</option>';
}
return $cat_1;
}
public function show_cat_2()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_2 ORDER BY idcat_2 ASC");
$cat_2 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_2'] . '"';
$cat_1 .= '>' . $row['idcat_2'] . '</option>';
}
return $cat_2;
}
etc..
my goal is to keep the choices (select value) in fields after submit the form (reload page) while maintaining their functionality. you can do it? how could I do that? thanks
I have this for the dropdown that pulls from the database.
When the user select one of the dropdown, it should open a new page with the posted variable pulled from the dropdown value. how should i approach that with jquery ?
so far i have this
echo '<label><SELECT name="cd-dropdown" id="cd-dropdown" class="cd-select">'.'<br>';
echo '<OPTION VALUE="-1" selected>'."Choose Project".'</OPTION>';
while($row = oci_fetch_array($compCuttingResult,OCI_ASSOC)){
$projectName = $row ['PROJECT_NAME'];
echo "<OPTION name='valueSelected' VALUE='$projectName' class='icon-fab'>$projectName</OPTION>";
}
echo '</SELECT></label><br />';
echo '<label><SELECT name="cd-dropdown" id="cd-dropdown" onchange="myFunction()" class="cd-select">'.'<br>';
echo '<OPTION VALUE="-1" selected>'."Choose Project".'</OPTION>';
echo "<OPTION name='valueSelected' VALUE='test' class='icon-fab'>test</OPTION>";
echo '</SELECT></label><br />';
?>
<script type="text/javascript">
function myFunction(){
var myselect = document.getElementById("cd-dropdown");
var val = myselect.options[myselect.selectedIndex].value;
window.location = "https://www.google.co.in/#q="+val;
}
</script>