I am trying to create a smart form which will automatically limit the options available of a second drop down box.
Background:
I am creating a ticketing system and I would like for the user to select a site from the "Site Selection" drop down and then the "User Selection" drop down will only contain users linked to the site selected on the first drop down, all information populated from MySQL.
Future:
I would then like to list all the services associated to that user with tick boxes under "Select Affected Services"
My js is pretty poor. So far I have been able to find some code by searching here that has allowed me to write the User's Computer ID into a text field. But I cannot figure out how to capture the output and query for the Computer Name (different table) and display that as a tick box option or to use the same method to limit the next lot of selection boxes. All code listed below I have not cleansed yet, alpha phase.
I realise that I could do this in steps using PHP only, but I am trying to pretty up my coding here and there.
Displaying Drop Downs:
<h3>Assign Site</h3>
<select id="site_add" name="site_add" style="width:217px; height:20px !important;">
<option value="-1"></option>';
$o = "SELECT * FROM company_sites WHERE company_id = " . $company_id . " ORDER BY sitename";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
echo '<option value="' . $r['id'] . '">' . $r['sitename'] . '</option>';
}
<h3>Assign User</h3>
<select id="comp_add" name="comp_add_1" style="width:217px; height:20px !important;">
<option value=""></option>';
$o = "SELECT * FROM company_staff WHERE company_id = " . $company_id . " ORDER BY id DESC";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
$user_computer_id = $r['computer_id'];
echo '<option value="' . $r['id'] . '">' . $r['firstname'] . ' ' . $r['lastname'] . '</option>';
}
Current JS to output selected user's computer ID into text field:
<script type="text/javascript">
window.onload=function() { attachBehaviors(); };
//
function attachBehaviors() {
document.getElementById(\'person\').onchange=function() {
loadUser(this.options[this.selectedIndex].value); // <-- check this, may be incorrect
}
}
function loadUser(optionvalue) {
// Always set a default
if (optionvalue==\'\') {
return;
}
opts = optionvalue.split(\':\');
var name = opts[0];
var email = opts[1];
document.getElementById(\'computer_id\').value=name;
}
</script>
<select name="person" id="person">
<option value=""></option>';
$result=mysql_query("SELECT * FROM company_staff");
while($row=mysql_fetch_array($result)) {
$submit_firstname = $row['firstname'];
$submit_lastname = $row['lastname'];
$submit_staff_id = $row['id'];
$submit_computer_id = $row['computer_id'];
echo '<option value="' . $submit_staff_id . '">' . $submit_firstname . ' ' . $submit_lastname . '</option>\n';
}
echo '
</select>
<input type="text" id="computer_id" name="name" placeholder="name" />
';
Any recommendations on how to achieve this would be greatly appreciated!
Thanks in advance!
You need AJAX, it's a combination of PHP and JS. ( javascript request data from the server, php processes the request, returns data ).
You would need to practice AJAX a bit to understand how to make this select box.
This is process in theory:
You output your first select box with PHP.
Make an onchange event handler for it that would call a server for information.
..options..
This updateNewDropDown function will take the value form a server response you selected and fetch the new data via PHP for the second select menu, and create the new select menu with the data AJAX response provided.
AJAX TUTORIALS:
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/ajax/default.asp
Related
I have a form consisting of 11 elements (input and select tags). The form has form validation that prompts an error message next to field when a user inputs incorrect data. I want to maintain the correct data entered into the fields after the page is refreshed.
For instance, let's say that 10 fields where populated correctly and 1 field incorrectly. When the user presses the submit button, an error message is shown near the field. What I want to do is to keep the 10 correct values selected so the user does no have to start all over again.
For the input elements, this is working fine but for the select elements this is not working. Important is that I am populating the drop down list dynamically with PHP.
Is this possible to do in PHP since I cannot figure out how?
Below is an example of how I am generating a drop down list of a select element.
select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
echo '<option value="' . htmlspecialchars($row['description']) . '">'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As for the input elements I am achieving this using the below:
<input type="text" name="serial" value="<?php echo $serial;?>">
Try this:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As outlined in the as duplicate linked question the selected attribute is to mark the option that has been submitted. The selected attribute addresses the issue to make the selected value visible.
Additionally your code can benefit from data-binding the select element to the (SQL) data in a modular way.
Let us not care for a moment on the retrieval of the data and just say they come from a Generator:
/**
* #param string $name of the select field
* #param string $value of the select field
* #param Generator $data to use as select field option values
* #return string HTML of the select element
*/
function select($name, $value, Generator $data) {
$buffer = sprintf('<select name="%s">', htmlspecialchars($name));
foreach ($data as $option) {
$buffer .= sprintf(
'<option%s>%s</option>',
$value === $option ? ' selected' : '',
htmlspecialchars($option)
);
}
$buffer .= "</select>\n";
return $buffer;
}
This little function returns the HMTL of a select element with the data from a Generator selecting an existing value (if part of the options).
Combining it with any generator, for example from a data-source, it can be easily put into your forms template script:
<form method="post">
<?= select('location', $_POST['location'] ?? 'default value',
datasource($connection, "SELECT description FROM location ORDER BY description ASC", "description")
) ?>
</form>
So if you've got 10 selects, this can be easily adopted. As the database connection as you know it is passed to the datasource function, it would be interesting to see what that function actually does. That function is even more simple:
/**
* #param mysqli $mysqli
* #param string $query
* #param string $field from query result to use as option values
* #return Generator
*/
function datasource(mysqli $mysqli, $query, $field) {
$result = $mysqli->query($query);
if ($result) foreach ($result as $row) {
yield $row[$field];
}
}
It queries the query on the database connection (it's a different way of writing as in your code, but it's the same $connection as in your example) and then iterates over the result (if there is a result). Then yielding each option value. That yield is a special form of returning from a function creating a Generator which is used in the select function for output, by having the Generator in the foreach loop there. Each yielding becomes one iteration of the Generator.
I hope this shows how you can benefit from dividing your code into functions. Values that change should be put into variables. This is easily done by creating functions and using parameters for these values. You sort of extend the language to your own special needs, like creating select elements.
Is this possible to do in PHP since I cannot figure out how?
Yes it is possible to keep the values selected, by using the selected attribute on the option elements.
For instance, the <option> tag below contains that attribute:
<option value="value2" selected>Value 2</option>
If you care about XHTML validation, use selected="selected" - refer to this answer for more information.
<option value="value2" selected="selected">Value 2</option>
From the examples section of the MDN documentation for <select>, the following HTML is listed:
<!-- The second value will be selected initially -->
<select name="select"> <!--Supplement an id here instead of using 'name'-->
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Rendering a select list with PHP
To achieve this with the PHP code, the selected attribute needs to be conditionally added to the option.
First, before the while loop, store the selected location in a variable:
$selectedLocation = '';
if (isset($_POST['location'])) {
//Get selected value from values submitted with form
//use $_GET if form is submitted via GET
$selectedLocation = $_POST['location'];
}
Then in the while loop, set that selected attribute when the matching option is found (i.e. when $selectedLocation == $row['description']).
while($row = mysqli_fetch_assoc()){
$selected = ''; //default to empty string - not selected
if ($selectedLocation == $row['description']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['description']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
See a demosntration of this in this phpfiddle.
Edit and try:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
I am creating a website and need some assistance on how to create something similar to this:
https://matchstat.com/tennis/head-to-head
(the user can basically select any 2 players and compare their wins).
However, instead of typing into the search box, I will instead be using a drop down box, any ideas on how this can be achieved?
So far, I have set up my database and connected using the SQL, PHP.
A quick illustration of my form:
[select player] //this will be a drop down/options box
Forename: // the content of these fields will depend on what player the user has selected from the drop down / options box above
Surname:
Nationality:
DOB:
Height:
Weight:
Any advice would be appreciated.
Many thanks
If you have the SQL query results stored an a 2d array (rows x columns), you can simply loop through the results of the array to print out the <option>s for the drop-down <select> box like so:
<?php
$users = // SQL query result
echo "<select>";
foreach($users as $user) {
$data = $user["forename"];
echo "<option value='$data'>$data</option>";
}
echo "</select>";
?>
By request, here is a more complex solution that creates a drop-down box and allows the data to be shown. This also uses jQuery (plain JS could also be used, but jQuery simplifies a lot):
<select id="dropdown">
<?php
// this PHP is essentially the same as in the above example
$users = [ // this is the test array I used. The SQL result should be in the same format for this to work.
[
"forename"=>"a_name",
"dob"=>"never",
"height"=>"too_tall",
"weight"=>"too_heavy",
"nationality"=>"martian"
],
[
"forename"=>"second_name",
"dob"=>"always",
"height"=>"too_short",
"weight"=>"too_light",
"nationality"=>"moon"
],
[
"forename"=>"third_name",
"dob"=>"forever",
"height"=>"300ft",
"weight"=>"2000lb",
"nationality"=>"Earth"
]
];
$userDataArray = []; // multidimensional array
$user_id = 0;
foreach($users as $user) {
$data = $user["forename"];
echo "<option value='$user_id'>$data</option>";
$user_id++;
$userDataArray[] = [ "forename"=>$user["forename"], "dob"=>$user["dob"], "height"=>$user["height"], "weight"=>$user["weight"], "nationality"=>$user["nationality"] ];
// index 0 = forename, 1 = DOB, 2 = height, 3 = weight, 4 = nationality
}
?>
</select><br />
<span id="display"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><!-- load jQuery library -->
<script>
var users = [
<?php // translate PHP array to JS one
foreach($userDataArray as $user) {
echo "{ forename: '" . $user["forename"] . "', dob: '" . $user["dob"] . "', weight: '" . $user["weight"] . "', height: '" . $user["height"] . "', nationality: '" . $user["nationality"] . "'},";
}
?>
];
$("#dropdown").change(function() {
var i = $("#dropdown").val();
$("#display").html("Name: " + users[i].forename + "<br />DOB: " + users[i].dob + "<br />Weight: " + users[i].weight + "<br />Height: " + users[i].height + "<br />Nationality: " + users[i].nationality);
});
</script>
Sorry this answer is so long and confusing. I'm not sure if there is any simpler way, especially when dealing with two different languages (and yes, you need both to deal with the server (database with PHP) and the client (dropdown with JS). I hope this helps!
See the now correct output here at Ideone.
I have a mysql table with about 40 items in it. What I want to do is reference those 40 items in a form on my webpage with a drop down list.
Instead of writing it out all 40 items like the following to know if an item has been selected:
<!doctype html>
<html>
</head>
<body>
<select>
<option value="Health & Beauty"<?php if (isset($_POST['SiteType']) && ($_POST['SiteType'] == 'Health & Beauty')) echo ' selected="selected"'; ?>>Health & Beauty</option></select>
</body>
</html>
and so on 40 times...
I am wondering how I could do it instead by using an SQL statement like the following:
here is what I have so far.
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " . mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . '">' . $row2['SiteType'] . '</option><\select>';
}
The code above produces a nice drop down list, but I don't know how to make the database know when an item is selected by a user. What code do I write to make that happen? Can I use the SQL statement option or do I have to write each item out like I wrote at the beginning of this post.
This might help you
Add Select Attribute to your Table of type varchar
alter table user add Selected varchar(255)
Give them all values to '0'
and in html page
<select name="sitename">
<option></option>
<!-- your options -->
</select>
and when form is submitted by your you simply use this
echo $_POST['sitename'];
Then use this query to database know user selected this field in usertable or where you want
Update user set selcted='$_POST["sitename"]' where userid='currectuserid'
I hope I understood you right
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " .mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . ' '.($row2['SiteTypeName'] == $_POST['SiteType'] ? 'selected="selected"':'').'">' . $row2['SiteType'] . '</option><\select>';
}
I'm not sure if the syntax is right, but you get the idea.
Edit: as I Can Haz Cheeseburger suggested u need to get the name from the db (not id) or pass the ID through POST
I have created a PHP code to echo the following div
<div id="main_catsel">
<select id="maincat" >
<option value="1">none</option>
<option value="2">Computer</option>
<option value="4">Refrigerator</option>
<option value="13" selected="selected" >Grinder</option>
<option value="21">Bed</option>
</select>
</div>
I am using the option values and name as result from query . But now the default result still shown first is according to the id not according to selected="selected". Can any one sugsest a solution for this. Cant remove the id ,because its needed for insertion.
$maincat .='<div class="main_catsel">';
$sqlmaincat = $ilance->db->query("SELECT
cid FROM " . DB_PREFIX . "seller_profile
WHERE userid = '" . $uid . "'");
$row = $ilance->db->fetch_array($sqlmaincat);
$sqlcat = $ilance->db->query("SELECT
cid,title_spa
FROM " . DB_PREFIX . "categories
WHERE parentid = '0'
");
if ($ilance->db->num_rows($sqlcat) > 0)
{
$maincat .='<h2><select id="maincat">';
while ($rows = $ilance->db->fetch_array($sqlcat))
{
if($rows['cid']==$row['cid'])
{
$maincat .='<option selected="selected" value="'.$rows['cid'].'">'.$rows['title_spa'].'</option>';
}
else
{
$maincat .='<option value="'.$rows['cid'].'">'.$rows['title_spa'].'</option>';
}
}
$maincat .='</select></h2>';
}
$maincat .='</div>';
What browser are you using?
"On SGML and HTML" points out that some browsers only support the minimized form, i.e. selected rather than selected="selected".
Or maybe you previously selected something, and your browser is remembering your choice. Try holding Shift and clicking the Reload button, or press Ctrl+F5.
Or maybe the your browser is caching an older version of the page. Again Shift+Reload should help. Browser-specific details at Bypass your cache.
It seems that you just do like this
$("select#maincat").val("13");
Thats it. just try this and Let me know further.
I have a drop-down select tag for Patients:
<select>
<?php
$qPatient = mysql_query("SELECT idpatients, firstName, mi, lastName, suffix FROM patients ORDER BY lastName ASC");
while($rowPatient = mysql_fetch_array( $qPatient )) {
if(isset($rowPatient['suffix']) && !empty($rowPatient['suffix'])){$suffix = " " . $rowPatient['suffix'];}else{$suffix = NULL;}
if(isset($rowPatient['mi']) && !empty($rowPatient['mi'])){$mi = " " . $rowPatient['mi'] . ".";}else{$mi = NULL;}
echo "<option value=" . $rowPatient['idpatients'] . $rowPatient . ">" . $rowPatient['lastName'] . $suffix . ", " . $rowPatient['firstName'] . $mi . "</option>";
}
?>
</select>
This generates a list of patients from the drop-down.
How do I get the patientID based on the selection from my drop-down to put to my link?
ex: Update
where $idpatients = the patient ID from the drop-down list select tag.
Also, I need to have 3 different links: 1.) update.php 2.) chart.php and 3.) report.php
Set this form method to GET. After submiting, value of select field will be shown as get variable. So, add name to your select:
<select name="parientId">
And proper action to your form:
<form action="update.php" method="GET">
And, of course submit button.
This is "static way" with form". If you are sure that you want to have link, not submit button, you can do it with jQuery:
$("#go").click(function(){ $("#idOfYourForm").submit(); }
...
Go !
Or catch .change() (sorry, not select()) on your <select...> and set $("#go").attr('href','update.php?patientId='+$("#yourSelectId").val());
P.S.
Get from SQL only fields you need, not *
Update
<form...>
<select name="patientId" id="patientSelect">
...
</select>
<a id="updatelink" href="">....</a>
<a id="deletelink" href="">....</a>
<script type="text/javascript">
$(document).ready(function(){
$("#patientSelect").change(function(){
$("#updatelink").attr('href',"update.php?id="+$("#parientSelect").val());
$("#deletelink").attr('href',"delete.php?id="+$("#parientSelect").val());
}
});
</script>
Something like that, written fast, not checked/tested