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

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;
}
?>

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
{
} ?>

change select box value using other select box

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;

Check chekbox when value of another element is changed

I want to check checkbox when value of "select" is changed. No idea what is wrong with this code, maybe you will be able to see the mistake:
var selected; var div_id;
$(".live_editor_test").focus(function() {
selected = $(this).val();
div_id = $(this).closest("div").attr('id');
});
$(".live_editor_test").blur(function() {
if (selected != $(this).val()) {
$('#live-assigning_check_' + div_id).attr('checked', true);
}
});
live_editor_test is the class of the select.
div is the row element and parent of live_editor_test.
live-assigning_check is the checkbox id.
div_id increments as there is one row for each mySql query.
Thanks in advance.
.php :
echo "<span class='content-row live-row-8' style=\"$colorcov\">";
echo "<select class=\"live_editor_test\" name=\"live_editor[$i]\" style=\"width:65px;font-size:10px;\">";
echo "<option value=\"\" selected></option>";
foreach ($storage_access->userAuth($row1, $where) as $row45)
{
if ($row45->match_id > '0') { $selected = "selected"; } else { $selected = ""; }
echo "<option value=\"$row45->user_id\" $selected>$row45->user_name</option>";
}
echo "</select>";
echo "</span>";
echo "<span style=\"width:20px;display:table-cell;\"><input class='checkbox-row' id='live-assigning_check_$i' type='checkbox' name='checked[$i]' ></span>";
Use .prop() instead of .attr(). Also use change event for select box.
Note: assuming that '#live-assigning_check_' + div_id evaluates to valid checkbox id.
$(".live_editor_test").change(function() {
if (selected != $(this).val()) {
$('#live-assigning_check_' + div_id).prop('checked', true);
}
});

How to Set a Dropdowns Default Selection Based on the Logged in User

I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>

How to make 2 drop downs work with links to other pages in PHP/HTML?

I am still a beginner with PHP. I am having a problem with drop downs and links. I want to be able to choose an option in the drop down menu and it go to the specified page. For some reason only the links for the second drop down menu. (MUNICIPALITIES) will work correctly by linking to the specific municipality page. The crime drop down menu will not link to the specific crime page. I have included the code for the crime drop down and municipality drop down. I have also included the script below.
Ultimately my question is why aren't both drop downs functioning correctly with the link?
<script language="JavaScript" type="text/javascript">
function gopage(theLink) {
if (document.dropdown.theLink.value != "") {
location.href = document.dropdown.theLink.value;
}
}
</script>
<form name="dropdown">
<select name="theLink" onchange="gopage(theLink)">
<option value="ALL">Choose Crime associated with the Gang</option>
<?php
//echo 'NOWWWWWWWWWWWWWWWWWWWWWW';
if ($length3 <> 0) {
for ($m = 0; $m < $length3; $m++) {
$rows = $resultset3[$m][crime_name];
$trackchoices = $rows;
$options2 = "<option value=\"crimesmain.php?crime=$trackchoices\">$trackchoices</option>";
echo "$options2";
}
}
else if ($length3 == 0) {
$trackanswer = "NO CRIMES";
$options5 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options5";
}
?>
</select>
</form>
<br>
<br>
<form name="dropdown">
<select name="theLink" onchange="gopage(this)">
<option value="ALL">Choose Municipality associated with the Gang</option>
<?php
if ($length12 <> 0) {
for ($q = 0; $q < $length12; $q++) {
$rows2 = $resultset6[$q][municipality_name];
$trackchoices2 = $rows2;
//try
$options3 = "<option value=\"municipalitymain.php?mun=$trackchoices2\">$trackchoices2</option>";
//echo "<a href='municipalitymain.php?mun=$options3'>";
echo "$options3";
}
}
else if ($length12 == 0) {
$trackanswer = "NO MUNICIPALITY";
$options6 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options6";
}
?>
</select>
</form>
I think a better solution would be to pass the id of the select element to gopage so your function looks like this
function gopage(elId)
{
if (document.getElementById(elId).value != "") {
location.href = document.getElementById(elId).value;
}
}
First Dropdown
<select name="theLink" id="crime" onchange="gopage('crime')">
Second Dropdown
<select name="theLink2" id="muni" onchange="gopage('muni')">

Categories