reviernummer.onchange = function(){
var look=$("#reviernummer").val();
$("option[class='sorted']").hide();
$("option[title=look]").show();
};
The php code :
<label style="width:100px;float:left;">für das Revier:*</label>
<select class="required" id="reviernummer" style="width:240px;" name="verhaltenscode" ' >
<?php
$selected = $arrayAktuellerDatensatz['verhaltenscode'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('kataster', 'Fischereibuchzahl', 'Fischereibuchzahl'); ?>
</select><br />
<select class="required" id="verhaltenscode" style="width:240px;" name="verhaltenscode">
<?php $selected = $arrayAktuellerDatensatz['verhaltenscode_neu'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('helpbrutstatus', 'Brutstatus', 'Brutstatus');?>
</select>
loadselect function :
if ($tblname == 'kataster'){
$query = "SELECT * FROM kataster";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$fieldcaption = $row['Fischereibuchzahl'];
$lat = $row['Benennung']?>
<option title="<?php echo $lat; ?>" value="<?php echo $fieldvalue;?>"><?php echo $fieldcaption .' | '.$lat?></option> <?php
}
}
else if ($tblname == 'helpbrutstatus'){
$query = "SELECT * FROM helpbrutstatus" ;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$status = $row['Fischereibuchzahl'];
$fieldcaption = $row['Brutstatus']; ?>
<option value="<?php echo $fieldvalue;?>" title="<?php echo $status;?>" class="sorted">
<?php echo $status." | ".$fieldcaption?></option> <?php
}
}
I am trying to let all options disappear so i can make just some specific options be avaiable. What am i missing here in the last row of code? Can somebody help.
And sorry i couldn't find another answered question.
Thank you for your help.
You should concatenate String with variable using plus + signs, try the following code :
reviernummer.onchange = function(){
var look=$("#reviernummer").val();
$("option[class='sorted']").hide();
$("option[title='"+look+"']").show();
};
It will be better if you can use jquery on change event, try also :
$('#reviernummer').on('change', function(){
var look=$(this).val();
$("option[class='sorted']").hide();
$("option[title='"+look+"']").show();
};
Hope this helps.
Related
What i want to achieved is when a user pick or choose a speaker name on a dropdown list only the speaker expertise will show up in the next topic dropdown list. Ex. When He choose Ms. Cimatu the topic dropdown list must only show the topics that Ms. Cimatu is familiar like Motivational, Entertainment, Healtcare. And When the user choose Mr. Santos the topic dropdown list must only show the topics that he know like Business, and Technology. Btw the speakers names and topics that is show on the dropdown list is from a database that i get using select query and mysqli_fetch_array. Please guys any suggestions and help is really appreciated.
I already try this solution but my problem in this code is when i add new speaker, when i select their name it will not show any topics.
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
$selectspeakers = "SELECT * FROM speakers";
$sp_result = mysqli_query($conn, $selectspeakers);
$result = mysqli_query($conn, "SELECT speaker_fullname FROM speakers");
$storeArray = Array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$storeArray[] = $row['speaker_fullname'];
}
$msCimatuTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname = '$storeArray[0]' ";
$msCimatuTopics_result = mysqli_query($conn, $msCimatuTopics);
$mrSantosTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname ='$storeArray[1]' ";
$mrSantosTopics_result = mysqli_query($conn, $mrSantosTopics);
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<?php while($array = mysqli_fetch_array($sp_result)):;?>
<option value = "<?php echo $array['speaker_fullname'];?>" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_fullname'];?></option>
<?php endwhile;?>
</select>
</div>
<div class="form-group">
<label for="msCimatuTopics" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control hidden" id="msCimatuTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($msCimatuTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
<select name="topic" class="form-control hidden" id="mrSantosTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($mrSantosTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
</div>
</body>
</html>
<script>
$('#speaker').change(function(){
var selected_item = $(this).val()
if(selected_item == "Ms. Cimatu")
{
$('#msCimatuTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
}
else if(selected_item == "Mr. Santos")
{
$('#mrSantosTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#msCimatuTopics').val(selected_item).addClass('hidden');
}
else
{
$('#msCimatuTopics').val(selected_item).addClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
$('#topicTitle').val(selected_item).addClass('hidden');
}
});
</script>
this is the image of dropdown list
This is the image of the database data
There are some basic things you can look to improve with your implementation. The biggest is you don't need to keep querying the same table for different pieces of data. If you are okay with running the SELECT * on the speakers table then you can skip the rest of your queries.
The next task is to try and make your code less dependent on singular values. If you notice you are writing the same code for value 1, value 2, etc then try to think about how to abstract your code so that it can work for an unlimited number of values.
This is a very rough implementation based on your sample code implementing the items I've mentioned. I have no way of testing it so there may be some small errors you need to debug before it works for your purpose:
<?php
// Based on your code and image these appear to be the fields in the speakers table:
// speaker_fullname
// speaker_image
// speaker_videolink
// speaker_specialization1
// speaker_specialization2
// speaker_specialization3
// speaker_specialization4
// speaker_specialization5
// Make your connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Get speakers and all their data (you only need one query!)
$result = mysqli_query($conn, "SELECT * FROM speakers");
// Store the speakers for later
// (You could maybe use this instead but depends on your PHP version:)
// -> http://php.net/manual/en/mysqli-result.fetch-array.php
$speaker_array = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$speaker_array[] = $row;
}
// Apparently you have session values? You don't start the session though?
// See: http://php.net/session_start
$session_speaker_fullname = ( ! empty($_SESSION["selectedSpeaker"])) ? $_SESSION["selectedSpeaker"] : '';
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<option value=""></option>
<?php foreach($speaker_array as $row):;?>
<option value="<?php echo $row['speaker_fullname'];?>"
<?php if($session_speaker_fullname == $row['speaker_fullname']) echo "selected";?>
><?php echo $row['speaker_fullname'];?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="topic" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control" id="topic" style='text-transform:capitalize;' autofocus required="required">
<!-- this will get populated via JavaScript -->
</select>
</div>
<script type="text/javascript">
// Let your data be used by JavaScript
var speaker_array = <?php echo json_encode($speaker_array); ?>;
// A function to update the topic select
function update_topic_select_list() {
// Clear the current topic list
$('#topic').html('');
// Only re-build the topic list if a speaker is selected
if ($('#speaker option:selected').val() != '') {
var topic_array = Array();
// Find the correct speaker
for (var i = 0; i < speaker_array.length; i++) {
// The speaker name matches
if (speaker_array[i].speaker_name == $('#speaker option:selected').val())
// Add the values to the topic array
topic_array.push(speaker_array[i].speaker_specialization1);
topic_array.push(speaker_array[i].speaker_specialization2);
topic_array.push(speaker_array[i].speaker_specialization3);
topic_array.push(speaker_array[i].speaker_specialization4);
topic_array.push(speaker_array[i].speaker_specialization5);
// Stop the loop
break;
}
}
// Update the topic list
for (var i = 0; i < topic_array.length; i++) {
// Don't add empty values
if (topic_array[i] != '') {
$('#topic').append('<option value="' + topic_array[i] + '">' + topic_array[i] + '</option>');
}
}
}
}
// Watch for changes to the speaker selection
$('#speaker').change(function() {
// Do you need to do anything else?
// Call the update function
update_topic_select_list();
});
// Force a change trigger after page load - in case you need that session value set?
$('#speaker').trigger('change');
</script>
</body>
</html>
I would suggest to use AJAX. In this way, when the user selects a speaker, Javascript will request the server the list of specializations for the selected speaker. For example:
<!-- This is your <select> of speakers -->
<select id="select-speaker">
<?php echo($speaker_options); ?>
</select>
<!-- This is your <select> of specializations -->
<select id="select-specialization">
<option value=""></option>
</select>
<!-- This is your JS code -->
<script>
// When users select the speaker, #select-specialization gets updated
$("#select-speaker").change(function (){
var speaker = document.getElementById("select-speaker");
GetSpecializations(speaker.value).then(function (data){
document.getElementById("select-specialization").innerHTML = data;
});
});
async function GetSpecializations(speaker){
// Request the server via AJAX the list of specializations for that speaker
var options = await AjaxPOST("page.php", speaker);
// Returns something like "<option value='spec1'>Spec1</option>..."
return options;
}
</script>
This is just an idea. Here's a possible implementation of AjaxPOST():
function AjaxPOST(url, speaker){
return new Promise(resolve => {
var http = new XMLHttpRequest();
var params = {"sentFromAJAX" : "true", "speaker" : speaker};
http.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
resolve(this.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.send(JSON.stringify(params));
});
}
This is a basic AJAX tutorial from W3C and this is a useful article on async/await from MDN.
P.S.: I didn't test this code. But it should work.
P.P.S.: It's missing the PHP part of code. You have to handle AJAX requests sent from Javascript. Note that this code sends the params encoded in JSON, so in PHP you have to retrieve $_POST variable using something like: $_POST = json_decode(file_get_contents("php://input"), true) ?: [];.
I have created two select boxes each have different country names with flag images using select2 plugin and values are fetching from Database below is the code.
JS CODE
$(".currencyconverterselect").select2({
templateResult: addflag,
templateSelection: addflag
});
function addflag(opt) {
if (!opt.id) {
return opt.text;
}
var $opt = $(
'<span><img src="./img/flags/' + $(opt.element).attr('data-country-code') + '.png" class="userPic" /> ' + $(opt.element).text() + '</span>'
);
return $opt;
};
HTML CODE
<label style="color:white">Currency from</label>
<select name="fromcurrency_cc" id="fromcurrency_cc" class="form-control charts_currency" style="width:100%" required="required">
<?php
$sql = "SELECT fc.country_id,fc.code,fc.name,cc.country_code AS countrycode FROM fx_currency fc LEFT JOIN fx_country cc ON fc.country_id = cc.id ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row['code'] == 'AED')
{ ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>" selected>
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php } else { ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>">
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php }}
} else {
echo "0 results";
}
?>
</select>
I have also created a button below is the code
</i>
I want to swap the value of FROM currency to TO Currency and vice versa by clicking the button.
I have tried below code
$("#swapvalues_btn1").on('click', function() {
var pickup = $('#fromcurrency_cc').val();
$('#from').val($('#tocurrency').val());
$('#to').val(pickup);
});
Select2 will listen for the change event on the that it is attached to. If you make any external changes that need to be reflected in Select2 (such as changing the value).
Just use below code
$("#swapvalues_btn1").on('click', function() {
var fromcurrency = $('#fromcurrency').val();
var tocurrency = $('#tocurrency').val();
$('#fromcurrency').val(tocurrency).trigger('change');
$('#tocurrency').val(fromcurrency).trigger('change');
});
For More follow the link
https://select2.github.io/options.html#events
I know this is a stupid question but i am new with AJAX and
i tried many of the code i got from internet but still not able to do this simple thing
so at last i am posting my question here
something is wrong and when i select option in first drop down list
nothing happens
database table name is sub_menu and its fields are as follows
id,sub_item_name,item_name,price
this is my script i put on additem.php file
<script>
function showSubItem(sel) {
var item_name = sel.options[sel.selectedIndex].value;
$("#subItemTr").html( "" );
if (item_name.length > 0 ) {
$.ajax({
type: "POST",
url: "subitem.php",
data: "item_name="+item_name,
cache: false,
success: function(html) {
$("#subItemTr").html( html );
}
});
}
}
</script>
and he is my both drop down menu both are in a table form
My master menu is still working and displaying all option from database so i am not posting that
part here
<tr>
<td width="251">Select Master Menu Name</td>
<td width="47">:</td>
<td width="342"><select name="iname" id="iname" class="form-control" onChange="showSubItem(this);">
<option selected="selected">Select Main Menu</option>
<?php
$abc = "select * from main_menu";
$lkg = mysql_query($abc);
while($ukg = mysql_fetch_row($lkg))
{
?>
<option><?php echo $ukg[1]; ?></option>
<?php } ?>
</select> </td>
</tr>
<tr>
<td width="251">Sub Item Name</td>
<td width="47">:</td>
<td width="342" id="subItemTr" ><select name="subname" id="subname" class="form-control">
<option selected="selected">Select Sub Item</option>
</select></td>
</tr>
And here is my subitem.php file code as follows
<?php
include 'config.php';
$item_name = ($_POST["item_name"] <> "") ? trim( addslashes($_POST["item_name"])) : "";
if ($country_id <> "" ) {
$sql = "SELECT * FROM sub_menu WHERE item_name = ".$item_name ." ORDER BY sub_item_name";
$count = mysql_num_rows( mysql_query($sql) );
if ($count > 0 ) {
$query = mysql_query($sql);
?>
<select name="sub_item">
<option value="">Please Select</option>
<?php while ($rs = mysql_fetch_array($query)) { ?>
<option><?php echo $rs["item_name"]; ?></option>
<?php } ?>
</select>
<?php
}
}
?>
This should
<option><?php echo $rs["item_name"]; ?></option>
to
<option value="<?php echo $rs["item_id"]; ?>"><?php echo $rs["item_name"]; ?></option>
I given $rs["item_id"]; whatever field you want in value fix it.
And also,
change this line also
Your selectbox option should have value attributes. Until your condition if (item_name.length > 0 ) { should be fail.
<option><?php echo $ukg[1]; ?></option>
Should be
<option value="<?php echo YOUR_VALUE ?>"><?php echo $ukg[1]; ?></option>
<option><?php echo $rs["item_name"]; ?></option>
Should be
<option value="<?php echo YOUR_VALUE ?>"><?php echo $rs["item_name"]; ?></option>
Also currently you are sending the object instead on value.
<select name="iname" id="iname" class="form-control" onChange="showSubItem(this);">
Should be
<select name="iname" id="iname" class="form-control" onChange="showSubItem(this.value);">
So you can access the selected value directly from your variable sel
var item_name = sel;
You not defined the $country_id in subitem.php file, Thats why code fails to execute inside if statement. You define something for $country_id or remove the condition if not necessary. Then it will work
Example:
<?php
include 'config.php';
$country_id = 'something';
$item_name = ($_POST["item_name"] <> "") ? trim( addslashes($_POST["item_name"])) : "";
if ($country_id <> "" ) {
$sql = "SELECT * FROM sub_menu WHERE item_name = ".$item_name ." ORDER BY sub_item_name";
$count = mysql_num_rows( mysql_query($sql) );
if ($count > 0 ) {
$query = mysql_query($sql);
?>
<select name="sub_item">
<option value="">Please Select</option>
<?php while ($rs = mysql_fetch_array($query)) { ?>
<option><?php echo $rs["item_name"]; ?></option>
<?php } ?>
</select>
<?php
}
}
?>
I need the code for getting the addr and pnum of the patient when I choose the pname in the combo box.
How can I do that?
<script>
function getVal() {
document.getElementById("text2").value = document.getElementById("model").value;
}
</script>
<body>
//code in opening and getting my addr and pnum in dbase
<?php
include('connect.php');
$pname=$_GET['tpname'];
$result = mysql_query("SELECT * FROM tblnpatient where pname='$pname'");
while($row = mysql_fetch_array($result))
{
$pnum=$row['pnum'];
$addr=$row['addr'];
}
?>
//code for choosing pname
<tr><td>Patient Name:
<div id="ma">
<select name="pname" class="textfields" id="model" style="width:180px;" onchange="getVal();">
<option id="0" >--Select Patient Name--</option>
<?php
$con=mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pnum=$_GET['pnum'];
$query = mysqli_query($con, "SELECT * FROM tblnpatient");
while($row = mysqli_fetch_array($query)){
$pnum = $row['pnum'];
$pname = $row['pname'];
?>
<option id="<?php echo $pnum; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?> </option>
<?php } ?>
</select>
//code for getting pname and addr
Address:<input type="text" name="ename" size="20" id="ma" value="<?php echo $addr ?>"/>
Name:<input type="text" name="ename" size="20" id="ma" value="<?php echo $pname ?>"/>
In your while loop add the following (if you have that column otherwise replace with something similar)
$paddress = $row['paddress'];
You can store the needed information by using the data attribute in your options
<option id="<?php echo $pnum; ?>" data-pname="<?php echo $pname; ?>" data-paddress="<?php echo $paddress; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?></option>
Then change your getVal() function
function getVal() {
var options = document.getElementById("model").options;
if (options.selectedIndex != -1) {
var addr = document.getElementById('paddress');
var name = document.getElementById('pname');
addr.value = options[options.selectedIndex].getAttribute('data-paddress');
name.value = options[options.selectedIndex].getAttribute('data-pname');
}
}
Now change the id's of the input fields for the address and the name to paddress and pname. It is important to know to never have duplicate id's
I hope that helped
I am creating a dropdown list in php. how can i put the selected item when someone selects an item.
my php code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" ><option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
while($row=mysqli_fetch_array($result))
{
$selected = $row['name'];
echo "<option id=". $row['id']."value = ".$row['id'].">".$row['name']."</option>";
}
echo "</select>";
?>
i want this: if I select an item it will show it as selected. how can I do this
You can do it in php like
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" >
<option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
$selected_val = $_POST['app']; //Should be $_GET, $_POST, $_SESSION whatever your selected value is
while($row=mysqli_fetch_array($result))
{
if(trim($row['id']) == trim($selected_val)) //<== Change this line
$selected = 'selected="selected"';
else
$selected = '';
echo '<option id="'. $row['id'].'" value="'.$row['id'].'" '. $selected.'>'. $row['name'] .'</option>';
//^Change this line
}
echo "</select>";
?>
In jQuery you can do it like
$('#dropdown').val('<?php echo "My val"; //The value goes here ?>');
Assuming that you mean you want to retain the selection after the form is submitted, you can do this inside the while loop:
$selected = (isset($_POST['app']) && $_POST['app'] == $row['id'] ? 'selected' : '');
echo "<option id=".$row['id']." value = ".$row['id']." ".$selected.">".$row['name']."</option>";