adding value and name to select box - php

<?php
$sql = "SELECT `docid`, `fullname` FROM `doctors` ORDER BY fullname ASC";
$result = $database->query($sql) or die('cannot connect to the database');
while($row = mysql_fetch_array($result))
{
echo"<option value= ".$row['docid'].">".$row['fullname']."</option>";
}
?>
This is my select box which i am populating through datbase table.
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
i want to make this one as SELECTED ITEM ON THE Select box
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
});
This is my jquery code. When i click ".sheUpdate" link i have couple of values that i am grabing using attr function. i am grabing depatment name and department value which i want to show as the SELECTED ITEM ON THE SELECT BOX

I think we need to see more code to be able to properly help. What is the html code of the element with the .sheUpdate class?
Does this link element actually have attributes dptname and dptid?
What is the code you use on #Deptmentselectbox?

The code you added is working properly.
just need to set the new added element as selected.
please check this fiddle
Also please let me know what value you get if you write this
alert($(this).attr('dptname'));
alert($(this).attr('dptid'));
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
$("#Deptmentselectbox").get(0).selectedIndex = 0;
// OR $("#Deptmentselectbox").val(deptid);
});

Assuming that your initial select box is like this:
<select id="Deptmentselectbox">
<option value=''> Select a department </option>
</select>
To remove the placeholder on first option selected:
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
if($("#Deptmentselectbox").val() == '')
$("#Deptmentselectbox").html('<option value='+deptid+'>'+deptment+'</option>');
else
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>');
$("#Deptmentselectbox").val(deptid);
}

Here is a Solution Hope it Helps
$(document).ready(function(){
$("#test1").click(function(){
var data = $("#t").val();
var data1 = $("#r").val();
$("#try").prepend('<option value='+data+' selected="selected">'+data1+'</option>');
});
});
Click Here For Demo

Related

How can I best put a drop down list or select tag inside a html table - And then update a row if changed to mysql? complicated

I have a database containing a name and a status column. It contains data displayed in a table (obvious!). So, I want users to be able to select the status column's data and change it to any value listed in the drop down list. After the selection, they need to click a button that will update the selected row to the mySQL database.
How can I achieve this with PHP scripting and HTML?
Here is my code for displaying the data in a table on the website: (Pay no attention to phpReportGenerator.php- its only drawing the columns as per sql table)
<?php
include_once('includes/phpReportGenerator.php');
$prg = new phpReportGenerator();
$prg->width = "100%";
$prg->cellpad = "10";
$prg->cellspace = "0.5";
$prg->border = "1";
$prg->header_color = "#307D7E";
$prg->header_textcolor="#FFFFFF";
$prg->body_alignment = "left";
$prg->body_color = "#C6DEFF";
$prg->body_textcolor = "#000000";
$prg->surrounded = '1';
//$prg->font_name = "Boishakhi";
mysql_connect("localhost","username","password");
mysql_select_db("my_database");
$res = mysql_query("select * from table");
$prg->mysql_resource = $res;
//$prg->title = "Test Table";
$prg->generateReport();
?>
OR
Can somebody show me a easier/more effective way to do this?
Here is the sample code that you can use to update your mysql database by sending request to the server to access process_mysql.php :
<select onchange="update_mysql();">
<option value="1">option 1 </option>
<option value="2">option 2 </option>
</select>
Jquery function with ajax post request:
<script>
update_mysql(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"process_mysql.php",
data:"id="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
</script>

jquery php code to bind state and city from mysql database table

I have a form where in one table row a dropdown state field is there and in another tr another dropdown is there for selecting city, I need that before submitting the form when user selects a state from dropdown list automatically the city dropdown should fetch and display only those city from the selected state.
I don't want to use AJAX but want to do it with jquery.
Backend database has two tables one is state with two fields id and state, second is city table having 3 fields id, state and city where state is my foreign key.
How can I do it with jquery any help regarding this will be appreciated since I am a newbie, please help
If you don't want to use ajax you can always preload the full list of states with cities into a javascript object and call it from there.
Example:
<select id="stateDrop">
<option value="state1">State 1</option>
<option value="state2">State 2</option>
</select>
<select id="cityDrop"></select>
<script>
var cities = {'state1':['city_one', 'city_two', 'city_three'], 'state2':['city_four', 'city_five', 'city_six']};
$('#stateDrop').on('change', function(){
var cityList = cities[$(this).val()];
console.log(cityList);
var output = '';
$(cityList).each(function(k, v){
output += '<option value="'+v+'">'+v+'</option>';
});
$('#cityDrop').html(output);
});
</script>
Fiddle
If you want to avoid using an ajax call, you will need to build a mapping from state-id's to lists of cities. Then bind a function to the change event of the state select-element, and populate the city select-element with the values.
Assuming State ID 0 has the cities A and B, with city id's 0 and 1:
var map = [[{id:0,name:"A"},{id:1,name:"B"}]]
$("#states").on("change",function() {
var cities = map[$(this).val()];
$("#cities option").remove(); //remove previous options
$.each(cities, function(i,e) {
$("#cities").append('<option value="'+e.id+'">'+e.name+'</option>');
});
});
Example: http://jsfiddle.net/HQLQU/
The php/mysql part for building the JS-map could be something like this (untested!):
$query = "SELECT city_id, city_name, state_id FROM cities";
$result = mysql_query($query); //or preferably use a more modern extension
$cities = array();
foreach (mysql_fetch_assoc($result) as $row) {
$cities[$row['state_id']][] = array("id"=>$row['city_id'],"name"=>$row['city_name']);
}
echo "var map = " . json_encode($cities);

Cascading jQuery Dropdowns with JSON and Multiple MySQL Tables using PHP

I'm fairly new to PHP and MySQL, have a little experience with jQuery and almost no experience with JSON, just to give you some background. I am trying to implement cascading dropdowns in my form.
I have two tables:
|city|
|city_id INT| - PK
|city VARCHAR (45)|
|state_state_id INT | - FK
|state|
|state_id INT| - PK
|state VARCHAR (25)|
Here's my form:
State:<br />
<select name="state" id="stateName">
<?php foreach($rows as $row): ?>
<option value="<?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>"><?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>
</option>
<?php endforeach; ?>
</select>
<br /><br />
City:<br />
<select name="city" id="cityName"></select>
<input type="submit" name="work_order_submit" id="" value="Add Work Order" />
I populate the State dropdown with this query:
$query = "SELECT * FROM state WHERE 1 ORDER BY state";
try{
$stmt = $db->prepare($query);
$stmt->execute();
}catch(PDOException $ex){
//On production remove getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
Here's the jQuery I've created to run the JSON and populate the City dropdown with the cascaded values from the state dropdown when a state is selected:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName:$('#stateName').val()},
function(data){
var select = $('#cityName');
var options = select.prop('options');
$('option', select).remove();
$.each(data, function(index, array){
options[options.length] = new Option(array['city']);
});
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
And here's the code in the state-names.php file (I connect to the database before this code):
$rows = array();
if(isset($_GET['stateName'])){
$query = "SELECT city FROM city INNER JOIN state ON city.state_state_id = state.state_id WHERE state = :state ORDER BY city";
$query_params = array(":state" => $_GET['stateName']);
try{
$stmt = $pdo->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
//On production remove .getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
Nothing happens when I select the state in the form. I don't even get an error. I've tested the SQL and it runs fine and retrieves the values that I want, but for some reason that I can't figure out, the values aren't being cascaded into the City dropdown.
Any help is very much appreciated.
EDIT: As I'm doing more debugging and realizing a few things, this is what I've found so far. The JSON comes in like this:
[{"city":"Salt Lake City"},{"city":"Toole"},{"city":"Provo"},{"city":"St. George"}]
I now know the JSON is working correctly. When I changed the dropdown selection in the state dropdown to a state that I know had entries for the cities, the city dropdown showed blank 'option' fields for the number of entries that there actually were. So, using the answer below and MANY different tutorials on cascading dropdowns and chained dropdowns, I finally figured it out. I've submitted an answer with the working code.
Can you try:
$.each(data, function(index, array){
// new Option(text [, value, defaultSelected, selected]);
select.add(new Option(array['city'], index), null);
});
??
All of the code above worked except the jQuery function. Well, the jQuery worked for what I told it to do, not for what I really wanted the code TO DO... Big difference.
Here's the working jQuery that populates the city dropdown based on a selection made in the state dropdown:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName: $('#stateName').val()},
function(data){
var html = '<option value="';
var htmlEnd = '</option>';
var options = '';
var select = $('#cityName');
$('option', select).remove();
$.each(data, function(index, array){
options += html + array['city'] + '">' + array['city'] + htmlEnd;
});
$('#cityName').append(options);
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
Before, the code would find the number of entries and the select box would show this number, but the selections were blank. With this code, the number of entries is found, but the values for those entries also show. Hope this helps someone else later.

Getting a value from my sql database in Javascript?

I've been having a bit of trouble with this for a while, please can somebody shed some light onto this?
What's happening so far: When a button is clicked, a search statement occurs and an AJAX call is made and brings back a set of results (displayed as a table) these results coming from a table in mysql database called 'ticket. The values displayed from the ticket table are 'venue' 'date' 'time' 'tPrice'.
This 'tPrice' is a number which has been set i.e. 15/20/25 to represent the price of a ticket. This works and displays fine but I'm having a problem trying to get the value of the price of the ticket in Javascript, does anyone know how to refer to a number in a mysql table in JS?
What I'm wanting to do with this value is multiply it to the value of whatever number is selected from a drop-down menu. (this drop-down menu is also returned by AJAX as part of the results of the user's search, this search result page is written in php and echoes the drop-down menu as a column within the results table)
What I have so far is this:
function quantityChange() {
//Select the value of the drop down list
var quantity = $('.summary').html($('#showQuantity option:selected').val());
//get the value of the number from the tPrice column in 'ticket' table
var ticket = parseFloat($('#ticketprice').val());
//multiply them together
var total = quantity * ticket;
return (total);
After debugging in Firebug, it's giving me no errors but it's also not giving me any results...please, any help would be greatly appreciated! Thanks
EDIT:
The php code:
$postCodeSQL = "SELECT * FROM ticket WHERE locationID IN (SELECT locationID FROM location WHERE postCode LIKE '$pcSearch') ";
$postCoderesult = mysql_query($postCodeSQL) or die(mysql_error());
while ($pcRow = mysql_fetch_assoc($postCoderesult)) {
$venue = $pcRow['venue'];
$ticketPrice = $pcRow['tPrice'];
$date = $pcRow['date'];
$time= $pcRow['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td id=\"ticketprice\">&pound$ticketPrice</td>\n";
echo "<td >
<select name =\"showQuantity\" id=\"showQuantity\" class =\"showQuantity\" onchange=\"quantityChange()\" >
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
</select>
</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "</tr>\n";
}
Try this (change the trigger function)
$(document).ready(function() {
function quantityChange() {
//Select the value of the drop down list
var quantity = $('#showQuantity option:selected').val();
//get the value of the number from the tPrice column in 'ticket' table
var ticket = parseFloat($('#ticketprice').val());
//multiply them together
var total = quantity * ticket;
//console.log(total);
//console.log(ticket);
//console.log(quantity);
return (total);
}
// Need a simple trigger
$('#showQuantity').change(function() {
quantityChange();
});
});
As said , you have more than one element with the same ID.
So when you're writing a code to get the value by elemeny's id = troubles.
Try:
1.Change the next line:
onchange=\"quantityChange()\"
to:
onChange=\"quantityChange(this)\"
2.Change your function defining line to:
function quanitityChange(selElem){
3.change the next line:
var quantity = $('.summary').html($('#showQuantity option:selected').val());
to:
var quantity = parseFloat($(this).find(":selected").val());
4.Change:
echo "<td id=\"ticketprice\">&pound$ticketPrice</td>\n";
to:
echo "<td id=\"ticketprice\">&pound$ticketPrice<input type='hidden' id='ticketPriceHidden' value='".$ticketPrice."'></td>\n";
5.In your function again:
var ticket = parseFloat($(this).parent().find("input#ticketPriceHidden").val());
Works? What the output of quantity and ticket now?

Dynamic Dropdown List from SQL with JS

Please help, I have a dynamic JS table, so you can add and delete rows by clicking a button. One field that I need to add within the row is a select box, no problem so for and I use the following:
var cell2 = row.insertCell(1);
var sel = document.createElement('select');
sel.name = 'selRow' + rowCount;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cell2.appendChild(sel);
So the above creates a select box, named based on the row ID using rowCount. Where I’m stuck is I need to dynamically populate the options, I can do this with php using the following, but it is linking the JS and PHP that I’m stuck on:
$getProd_sql = 'SELECT * FROM products';
$getProd = mysql_query($getProd_sql);
$prov = "<select name=\"product\" id=\"product\" onChange=\"testajaxprod();\">";
$prov .= " <option value=\"0\" selected=\"selected\">Select Product</option>";
while($row = mysql_fetch_array($getProd))
{
$prov .= "<option value=\"$row[product_id]\">$row[product_name]</option>";
}
$prov .= "</select>";
Your help is very much appreciated.
Thanks,
B.
You can add PHP in the middle of your JS. PHP will run first and leave you with a file containing the values as if my magic.
To populate from PHP instead of producing your data in text you can do this.
$getProd_sql = 'SELECT * FROM products';
$getProd = mysql_query($getProd_sql);
while($prod = mysql_fetch_object($getProd))
{
?>
var text = documentElement.createElement('select');
documentElement.value = <?=$prod->value?>
<?
}
Notice the way you can break in and out of PHP with . Also saves you from writing "echo" or anything. You will have to replace the simple text box with your dropdowns or whatever.
Hope this helps

Categories