Dynamic Dropdown List from SQL with JS - php

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

Related

How to click all database buttons generated through php script using a singe button?

The problem i've run into is that i have multiple buttons generated through php from data mysql data base and i do not want to manually click them all(it can go over 150). How do i make a button in HTML or PHP to click them all? or How to select the ID of each button (not manually) to include it in the General button?
I have tried onclick="document.getElementByID('').click()" atribute on the button that i want to click them all but with no succes
This is the code that i have and the issue:
<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testcases';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
//fetching data
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM test1 ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
echo "<table style=\"position:absolute; left:10px; top:80px;\" border ='1px'>";
while ($row = $result->fetch_object())
{
echo "<tbody>";
echo "<tr>";
echo "<td><textarea id=\"row->date\">". $row->date ." </textarea></td>";
echo "<td><textarea id=\"row->testcase\">". $row->testcase ."</textarea></td>";
echo "<td><textarea id=\"row->percentage\">". $row->percentage ." </textarea></td>";
echo "<td><a href='temp.php?id=" . $row->id . "'><button type=\"button\" class=\"btn\" name=\"id\" id=\"$row->id\" >COPY To Temp</button></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
}
}
// close database connection
$mysqli->close();
?>
<button type="button" style="width:200px" class="pure-button fuller-button1 blue" onclick="document.getElementByClassName('btn').click();">Copy All</button>
The expected result would be to have a table with multiple rows and button generated through php and another button to click them all, but i got stuck at the part where i need to click all the buttons.
I don't know what you really wanna do, but first of all it's a really strange thing to put a button into a link: if you want a like you can add a span child styled like a button and if you really want a button just listen to click events on it.
Another thing would be that you could use form + checkboxes so that your button can make a single action by submitting form (and this single action/HTTP query will be exploded in N actions (loop) server-side)
If you really would like to do this like you do, using ID property is not wrong but it doesn't help readability nor CSS selection, I would use data-* attributes.
So, now you want a simple answer ;)
var elements = document.getElementsByClassName("btn");
for (var i=0; i<elements.length; i++) {
elements[i].click(); // or anything you want
}
If you wanna get id properties you can do:
var elements = document.getElementsByClassName("btn");
var ids = [];
for (var i=0; i<elements.length; i++) {
ids.push(elements[i].id);
}
If you plan to use jQuery:
var ids = [];
$(".btn").each(function() {
var $button = $(this);
ids.push($button.attr("id"));
});
try this:
<button type="button" onclick="copyBtn()">Copy</button>
and using jQuery
function copyBtn(){
var id = $(this).attr("id");
console.log(id);
//do some stuff
}

Default value for select element from PHP

I have created a contacts database using PHP, MySQL on a XAMPP server.
The page opens with a 'Contacts' table with Add, Edit & Delete buttons.
Add & Delete are working fine.
Edit button opens a modal form with all the usual inputs which are filled in with values from the table row using...
$("#dlgeditContactName").val(ContactName);
$("#dlgeditEmail").val(Email);
etc.
There is also a select element (Contact Type) which is populated using PHP...
<?php
$conn = new mysqli('xxxx', 'xxxx', 'xxxx', 'xxxx') or die ('Cannot connect to db');
$result = $conn->query("select contacttypeid, contacttype from tblcontacttypes");
echo "<select id = 'dlgeditcontacttypeid'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
echo '<option value = "'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
The contacttypeid & contacttype are int and string eg.
1, Personal
2, Family
etc.
At the moment this select box acts as expected and user can choose an option during an edit session.
I just don't know the best way to put a default value in this select box based upon what's in the value in the table row.
Filling the other input elements was easy but using the following for the select does not work...
$("#dlgeditcontacttypeid").val(ContactTypeID);
I think I will have to use 'selected' as in ...
<option value="audi" selected>Audi</option>
(from W3Schools), but not sure if this is best or even how to do it.
I thought of a hidden div on the form with the ID but no luck getting the value to PHP
I tried putting some Java inside the PHP ...
echo "<script> function(); </script>";
but it looks 'messy' and I don't believe it's the best approach
There must be a standard method for this issue - anyone had to deal with this?
Is this what you are looking for:
$ContactTypeID = 2; //Considering you have default value with you.
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
if($id == $ContactTypeID) //If default value and id in loop are same
echo '<option value = "'.$id.'" selected="selected">'.$name.'</option>';
else
echo '<option value = "'.$id.'">'.$name.'</option>';
}

adding value and name to select box

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

Server side cascading dropdown in PHP

As I only have one value in the first dropdown, I am trying to create a cascading dropdown in PHP that populates the second dropdown on page load.
My database has a table called 'nights' with fields called: 'city', 'name' and 'day'.
To fill my first box I'm using SELECT DISTINCT cities from nights etc which has worked fine.
To fill the second box I need something along the lines of SELECT name WHERE city = $city - my problem is that I'm not sure how to set $city (being the name of the <select> tag). I can't use $_POST['city'] because the form hasn't been sent at this point.
Any ideas?
If you want this to be dynamic (i.e. after the user changes the dropdown) you will have to use javascript to firstly query a PHP page (probably using jQuery get) then adjust the dropdowns accordingly. There are lots of tutorials for this on the web.
If you just want the initial page data to be populated you can pick the first city from your query and set the option as selected, then use that city in your next query.
Something like:
$first = True;
while($row = mysql_fetch_array($result))
{
echo "<option" . (($first) ? " selected" : "") . ">" . $row['city'] . "</option>";
if($first)
{
$first = !$first;
$city = $row['city'];
}
}
//now do stuff with with $city
<?
$CITIES = query_result("SELECT DISTINCT cities FROM nights;");
if (isset($_POST["city"])) {
$NAMES = query_result("SELECT name FROM nights WHERE city = '{$_POST[city]}'");
if (isset($_POST["day"])
$DAYS = query_result("SELECT day FROM nights WHERE city='{$_POST[city]}'".
" AND name = '{$_POST[name]}'");
else
$DAYS = array();
} else
$NAMES = array();
/* now output the <select> markup for $CITIES, $NAMES and $DAYS */
?>
Note: you have to define the query_result function yourself (I just used it to simplify the code).
You can use AJAX for this.
On change event call javascript-ajax function that call php script which makes you second dropdown caode.
You will need to use ajax to load options from php script.
Here is an example of how you can do it with jquery and ajax:
Autopopulate Select Dropdown Box Using jQuery

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?

Categories