retrieve selected value in row using javascript - php

I've a table with multiple rows, each row has a drop down list. I am new to javascript and is unable to retrieve the selected value from the row. Any idea how can it be done? Thanks in advance.
Code:
function chng_page(serialNum, rowid)
{
alert(rowid);
alert(serialNum);
var select_index = document.getElementById('orderStatus').selectedIndex;
//get the value of selected option
var option_value = document.getElementById('orderStatus').options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
</script>
//code for drop down list
<select id="orderStatus" name="orderStatus" onchange="chng_page(<?php echo $serialNum? >, this.parentNode.parentNode.rowIndex)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>

You didn't mention if the select element in each row has a unique id or not, but it somehow shows in your code that they do.
In that case, you can use JQuery (a popular JavaScript framework) to retrieve the selected value.
Assuming you have included the JQuery file in your HTML, and attached an event handler to the select element (to make it easier, pass in the id of the current select element as a parameter in the function), do this:
var selected_value = $("#id_of_select_element option:selected").val();
If the ids of the select elements are unique, that single line of code will definitely work.

You have the same name/id for the drop down in all table rows

If there is a dropdownlist in each row with same id-> #orderStatus, you should try this,
function chng_page(serialNum, ddlist)
{
var rowid = ddlist.parentNode.parentNode.rowIndex
alert(rowid);
alert(serialNum);
var select_index = ddlist.selectedIndex;
//get the value of selected option
var option_value = ddlist.options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
<select name="orderStatus" onchange="chng_page(<?php echo $serialNum?>, this)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>

Related

Preselect dropdown options in a MySQL database table using php MySQLi [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am coding a PC repair application using MySQLi. I have an ENUM row in my database called "item_for_repair". In the ENUM list is Laptop, Desktop etc etc.
On my front end html table, when i click edit on a specific job card, under "item for repair" there is a drop down that always has the first value (for example, Laptop) selected and not the actual item that was stored (for example, Desktop), i need the drop down to be pre-selected with the item for repair that was originally stored in the database when storing the job card.
Here is an example image of what is happening. The item for repair in the databse is Desktop, but here you can clearly see its showing Laptop.
My code to connect to database as well as select all from the database:
<?php include 'settings.php'; //This file has all the database connection settings etc.
?>
<?php
$eid=$_GET['editid'];
$ret=mysqli_query($conn,"select * from pcrepairs where job_number='$eid'");
while ($row=mysqli_fetch_array($ret)) {
?>
And here is the select box code:
<select name="item_for_repair" id="item_for_repair">
<option value="Laptop" <?= $item_for_repair === 'Laptop' ? 'selected' : '' ?>>Laptop</option>
<option value="Desktop" <?= $item_for_repair === 'Desktop' ? 'selected' : '' ?>>Desktop</option>
<option value="Television" <?= $item_for_repair === 'Television' ? 'selected' : '' ?>>Television</option>
<option value="Washing Machine" <?= $item_for_repair === 'Washing Machine' ? 'selected' : '' ?>>Washing Machine</option>
<option value="Tumble Dryer" <?= $item_for_repair === 'Tumble Dryer' ? 'selected' : '' ?>>Tumble Dryer</option>
<option value="Dishwasher" <?= $item_for_repair === 'Dishwasher' ? 'selected' : '' ?>>Dishwasher</option>
<option value="Microwave" <?= $item_for_repair === 'Microwave' ? 'selected' : '' ?>>Microwave</option>
<option value="Fridge" <?= $item_for_repair === 'Fridge' ? 'selected' : '' ?>>Fridge</option>
<option value="Printer" <?= $item_for_repair === 'Printer' ? 'selected' : '' ?>>Printer</option>
<option value="Other" <?= $item_for_repair === 'Other' ? 'selected' : '' ?>>Other</option>
</select>
Where have i gone wrong?
Here is a complete example of how to populate an HTML select retrieving data from a MySQL database using MySQLi
<?php
class Country {
public $code;
public $name;
function __construct($code, $name) {
$this->code = $code;
$this->name = $name;
}
}
define("HOST", "localhost");
define("USERNAME", "root");
define("PASSWD", "");
define("DBNAME", "shop");
function country_select_list() {
$array = null;
$link = mysqli_connect(HOST, USERNAME, PASSWD, DBNAME);
$stmt = mysqli_prepare($link, "select code, name from country order by name");
if (!mysqli_execute($stmt)) {
throw new Exception(mysqli_stmt_error($stmt));
}
$code = null;
$name = null;
mysqli_stmt_bind_result($stmt, $code, $name);
while (mysqli_stmt_fetch($stmt)) {
$array[] = new Country($code, $name);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
return $array;
}
$user_country = 'CHE';
?>
<select id="user_country" name="user_country">
<option value=""></option>
<?php
foreach (country_select_list() as $country) {
echo ' <option value="' . $country->code . '"';
if (isset($user_country) && $user_country == $country->code) {
echo ' selected="selected"';
}
echo ">" . $country->name . "</option>\r\n";
}
?>
</select>
This is the output
<select id="user_country" name="user_country">
<option value=""></option>
<option value="ITA">Italy</option>
<option value="CHE" selected="selected">Switzerland</option>
</select>

retain dropdown select values after refresh with php session variables

Iam trying to make a dropdown select "sticky", basically I need to retain the value of the dropdown select in a session variable, then use the session variable in the doprdown select, so that when the page is refreshed, the value is retained in the dropdown select. I am trying to do this in php.
Here is the code for the select :
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach ($dirs as $p => $w):
$selected = $countryId === $w ? 'selected' : '';
echo '<option value="' . $w . '" ' . $selected . '>' . $w . '</option>';
endforeach;
?>
Any advice is greatly appreciated
make a second file called savesession.php
<?php
if (isset($_GET['country_option'])) $_SESSION['country_option'] = $_GET['country_option'];
then change your code to be
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : isset($_SESSION['country_option']) ? $_SESSION['country_option'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach($dirs as $p => $w):
$selected = $countryId===$w ? 'selected' : '';
echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
endforeach;
?>
<script>
function onDropDownChange(){
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
var ajax = new XMLHttpRequest();
ajax.open("GET", "yourpage.com/savesession.php?country_option=" + selectedItem, true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
}
}
}
</script>
then add an onchange="onDropDownChange" and id="dropdownID" to the <select> so that it calls a javascript function onDropDownChange

SELECT bit-value in db worked on NAS, not on server

I have some comboboxes with yes/no (value 1/0) that I store as a bit in my db. To put that value in the correct member of my object I do this:
class Member {
var $active;
public function refreshData() {
$mysqli = connectdbMySQLI();
$query = "SELECT * FROM tblMember WHERE ID = " . $this->id;
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$this->setData($row);
$mysqli->close();
}
public function setData($row) {
$this->active = $row['active'];
}
}
Alle varchars, int and text-values or being assigned, except these bit values.
I checked with var_dump and I get an empty string
["active"]=> string(1) ""
Saving doesn't work as well:
$member = new Member(isset($_POST['id']) ? $_POST['id'] : null );
if(isset($_POST['active'])) {
$member->active = $_POST['active'];
$member->save();
}
This I use to select the right value in the combobox:
<select type="text" name="active" id="active" class="txt">
<option value="0" <?php echo $member->active == 0 ? 'selected="selected"' : ''; ?>>No</option>
<option value="1" <?php echo $member->active == 1 ? 'selected="selected"' : ''; ?>>Yes</option>
</select>**
What can be different than on my local NAS?
EDIT:
I tried this (all results are 1):
$this->active = $row['active'] == true ? '1' : '0';
and this (all results are 0):
$this->active = $row['active'] == 1? '1' : '0';
EDIT 2:
just tried a simple query (no mysqli) and I get an empty result for all my bit-fields
the following condition will only work if you have selected the value 1 from the active dropdown
if(isset($_POST['active']))
you need to replace it with the following
if(!$_POST['active']) {
$_POST['active'] = 0;
}else{
$_POST['active'] = 1;
}
OR Solution 2
update the following values in drop down
<select type="text" name="active" id="active" class="txt">
<option value="1" <?php echo $member->active == 1 ? 'selected="selected"' : ''; ?>>No</option>
<option value="2" <?php echo $member->active == 2 ? 'selected="selected"' : ''; ?>>Yes</option>
</select>**
it will not bypass your if condition.

AM / PM value not displaying correctly in Select attribute

I have a list of items, each with a date/time option. I need for each list item to have the correct time displayed for it.
But this doesn't seem to work. It will return the correct 'am' or 'pm' value for $duedateA, but when I try to set the selected attribute value is gets wonky and will either show the wrong am or pm, or both.
Am I doing something wrong?
if(!empty($resInvoice[0]["due_date"])){
$duedateA = date("a",strtotime($resInvoice[0]['due_date']));
}
if($duedateA == "am"){
$selected_am = 'selected="selected"';
}
if($duedateA == "pm"){
$selected_pm = 'selected="selected"';
}
<select name="due_time[a]">
<option value="am" '.$selected_am.'>am</option>
<option value="pm" '.$selected_pm.'>pm</option>
</select>
date_default_timezone_set('America/New_York');
$resInvoice[0]["due_date"] = '2012-10-26 03:21:44';
$selected_am = '';
$selected_pm = '';
$duedateA = '';
if(!empty($resInvoice[0]["due_date"])){
$duedateA = date("a",strtotime($resInvoice[0]["due_date"]));
}
if($duedateA == "am"){
$selected_am = ' selected="selected"';
}
if($duedateA == "pm"){
$selected_pm = ' selected="selected"';
}
echo '<select name="due_date[a]">
<option value="am"'.$selected_am.'>AM</option>
<option value="pm"'.$selected_pm.'>PM</option>
</select>';
sorry for all the variables, i have my errors set to strict.

Select Combobox values in PHP with MySql Result

I am looking for some method to select a php combobox "<select>" based on results from mysql.
Actually I am working on a php form that will be used to edit existing values in mysql table. My first form will simply pass the id of the record to be edited, and this goes something like this Click to edit
Code on editCalendar.php is as follows:
<?php
include("dbpath.php");
$id = htmlspecialchars($_GET["id"]);
$sql="Select * from event_Date where eventid=" . $id;
$result=mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result))
{
$name=$row["EventTitle"];
$close=$row["OpenOrClose"];
$remarks=$row["Remarks"];
$date=$row["EventDate"];
$type=$row["Type"];
}
?>
The value obtained in $close will be used to select "SelectClosedOrOpen" on the same form, i.e. the user will get pre selected option from the populated list.
<select id="SelectClosedOrOpen">
<option value="3">Select</option>
<option value="0">Open</option>
<option value="1">Closed</option>
</select>
Means, if $close has 0, then <option value="0">Open</option> must be selected else if $close has 1 then <option value="1">Closed</option> should be automatically selected on formload.
You'll just need to write the selected attribute in there. Try this
<select id="SelectClosedOrOpen">
<option value="3" <?php echo ($close == 3) ? 'selected="selected"': ''; ?>>Select</option>
<option value="0" <?php echo ($close == 0) ? 'selected="selected"': ''; ?>>Open</option>
<option value="1" <?php echo ($close == 1) ? 'selected="selected"': ''; ?>>Closed</option>
</select>
I created this function some years back. I hope it helps you.
It basically requires an array of your options and the value of the option to be pre-selected. It returns the OPTIONS for your select, so you still have to create the SELECT tags, which allows you to customise the ID, JS etc..
function drop_down_box_options_from_array($choices,$default="")
{
$output= '';
// $choices is contructed using $choices[]=array("value","Displayed Choice");
while (list ($key, $val) = each ($choices))
{
$output.= '<option value="';
$output.= $choices[$key][0];
if ($default==$choices[$key][0])
{
$output.= '" selected="selected" >';
}
else
{
$output.= '">';
}
$output.= $choices[$key][1];
$output.= '</option>';
$output.= "\n";
}
return $output;
}
Using your scenario:
<select id="SelectClosedOrOpen" name="OpenOrClose">
<?php
// defined here for clarity, but can be defined earlier ie in a config file
$choices[]=array('3', 'Select');
$choices[]=array('0', 'Open');
$choices[]=array('1', 'Closed');
echo drop_down_box_options_from_array($choices, $row['OpenOrClose']);
?>
</select>

Categories