Count & Highlight Table Row Elements Dynamically - php

I want to be able to do two things. The first, is look at all "selected" items of a certain value. Say I have a, b, c ; I want to look for all items selected as "c" and highlight that table row as a different color. In addition, upon opening the form, I want the items counted, and be able to display a message div at the top of the screen showing those highlighted items. What is the best practical way of doing this? This is my original code :
//Start loop of items
<?php foreach ( $data['Detail'] as $key=>$item){?>
<tr id="tr_<?php echo $key+1?>">
<td>
<select value="<?php echo $location; ?>" name="[<?php echo $key;?>][location]" id="location_<?php echo $key+1?>" class="form-control>
<option value="Selection1" <?= ($item['location']) == 'Selection1' ? 'selected' : '' ?>>Selection1</option>
<option value="Selection2" <?= ($item['location']) == 'Selection2' ? 'selected' : '' ?>>Selection2</option>
<option value="Selection3" <?= ($item['location']) == 'Selection3' ? 'selected' : '' ?>>Selection3</option>
</select>
</td>
</tr>
// Segment here to count? Example :
// $location_count = 0; If $location = 'c' then $location_count++;
<?php } ?>
Sample Div Code :
<div>
<p>You have <?php echo $location_count?> Locations that need reviewed</p>
</div>
Image Sample of Working Code :

the theory is:
loop through the table's select elements
check each select's value and update the row style
when a select changes, do the same to the current row.
count the rows with the highlight
append the row count to the div
You can see the theory in practice with the code/link below.
The code is purposefully simplistic for demonstration and could be improved for performance/terseness. However it's not bad code :)
$(function() {
/* function to run for select boxes in table */
function rowState( $select ) {
var selected = false;
/* set boolean for selected */
if ( $select.val() === "c" ) {
selected = true;
}
/* apply css class to the row if selected */
$select.closest("tr").toggleClass("c", selected);
/* count rows */
var n = $( "table tr.c" ).length;
/* change the html element's text to the count */
$( ".snippet span" ).text( n );
}
$("table select").each(function() {
/* on page load, set selected states */
rowState($(this));
}).on("change", function() {
/* on state change, set selected states */
rowState($(this));
});
});
table {
width: 100%;
}
tr td {
background: #eee;
}
tr.c td {
background: #cfc
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="snippet">
Please review <span>x</span> items
</div>
<table>
<tr>
<td>
<select>
<option value="a" selected>a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option value="a">a</option>
<option value="b">b</option>
<option value="c" selected>c</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option value="a">a</option>
<option value="b" selected>b</option>
<option value="c">c</option>
</select>
</td>
</tr>
</table>

Related

Dynamic dropdown with auto select one option and it's sub-dropdown options

I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload

After clicking filter button values reseting

I've created list of entries from database via HTML table via PHP. There is filters: dropdown (select options) list and text filter.
PHP looks like:
<!DOCTYPE html>
<?php session_start();
ob_start();?>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<form method="post" action="<?php $_PHP_SELF ?>">
<label for="rank">Rank applied</label>
<select id='english' name="RankApplied" class="test">
<option selected disabled value="0">Select value</option>
<option name="RankApplied" value="1">One</option>
<option name="RankApplied" value="2">Two</option>
<option name="RankApplied" value="3">Three</option>
</select>
<label for="VesselsType">Vessel's type</label>
<input id="VesselsType" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
<input type="submit" name="submit" value="Filter" />
</form>
<?php
require("connect.php");
include '../../wp-load.php';
$RankApplied = $_POST["RankApplied"];
$VesselsType = $_POST["VesselsType"];
$UserID = get_current_user_id();
if(isset($UserID)) {
$users = $con->prepare("
SELECT DISTINCT CONCAT(FirstName, ' ', LastName) AS FullName,
RankApplied,
VesselsType
FROM tbl
WHERE FirstName <> ''
AND (RankApplied = '$RankApplied' OR '$RankApplied' = 0)
AND (VesselsType = '$VesselsType' OR '$VesselsType' = '')
");
$users->execute();
$users->bind_result($FName, $RankApplied, $VesselsType);
} else {
echo "There is no User ID detected, try to refresh browser.";
}
?>
<table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Vessel Type</th>
<th>Preview</th>
</tr>
<?php
while ($users->fetch()) {
?>
<tr>
<td><?php echo $FName; ?></td>
<td><?php echo $RankApplied; ?></td>
<td><?php echo $VesselsType; ?></td>
<td>View</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
If I select for example RankApplied = 'Two' and VesselsType = 'FooBar' after clicking Filter button It filter results correctly, but values for those fielters reseting (RankApplied = 'Select value' and VesselsType = ''), after clicking edit button It should keep/save chosen values.
The code isn't outputting those values. For example:
<input id="VesselsType" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
That just outputs an empty input. Nowhere does it include the value which was posted. You get the value here:
$VesselsType = $_POST["VesselsType"];
Just get it further up the page so you can use it in the output. Perhaps something like this:
<input id="VesselsType" value="<?php=$VesselsType ?>" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
The same concept applies for the select, but is slightly more involved. In that case you'd check if the value equals what was posted and set the selected attribute on an option element. There are a number of ways to do it, and my PHP is very rusty, but something like this might do the trick:
<option <?php echo isset($_POST["RankApplied"]) ? "" : "selected"; ?> disabled value="0">Select value</option>
<option <?php echo $RankApplied == "1" ? "selected" : ""; ?> name="RankApplied" value="1">One</option>
etc...
However you do it, the point remains the same. You need to output those values to the page in order for those values to be on the page.
You can save values with SESSION['rank'] and SESSION['type'] for example and display them when it's filtered.
When user sets the filter and hits the button give those values to session variables and display them.

php drop down button selected

in form edit data wants to display in the form...but drop down values should not get selected ...i want drop down value get seleted
here is code in list_search function id return cmb_fruit, val return Apple or Orange
<tr>
<td width="38%" height="28" align="left"><span class="style20"><font color="#DC143C">*</font>Profession</span></td>
<td width="62%" align="left"><label for="profession"></label>
<select name="cmb_fruit" size="1" id="cmb_fruit">
<option value="Select">Select</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select>
<script language="javascript" type="text/javascript">
list_search('cmb_fruit',<?php echo "'" . #mysql_result($rs_modify,0,'fruit') . "'";?>)
</script>
</td>
</tr>
function list_search(id,val)
{
cnt=document.getElementById(id).length
for(x=0; x<cnt; x++ )
{
if( document.getElementById(id).options(x).value==val)
{
document.getElementById(id).options(x).selected=true
break;
}
}
}
var fruit = document.getElementById("fruit");
fruit.options[fruit.options.selectedIndex].selected = true;
You can set the value property of the select. Also, make sure the list_search function is declared in the head if you are calling it from a script that runs in the body.
function list_search(id, val) {
document.getElementById(id).value = val;
}
Note that you don't need javascript for this and you could simpy put the selected attribute on the option element you want to select.
<option value="Apple" selected>Apple</option>

Remove select tag with text input if user select the certain option which cascade that

I want to make that if user is select certain option(provided from database) only one value then the other option tag appear to select else for all rest of other options user have text box to enter the value. Something like the below-
<tr>
<td><span class="alert">* </span>Country:</td>
<td><select name="country_id" class="medforminput" id="country_id" onchange="getState('select_state.php?country_id='+this.value)">
<option value="Select Country">Select Country</option>
<?php
while($row4=mysql_fetch_array($coun1))
{ ?>
<option value="<?php echo $row4['country_id']; ?>">
<?php echo $row4['country_name']; ?></option>
<?php }?>
<option value="others">Others</option>
</select></td>
</tr>
<tr>
<td><span class="alert">* </span>State</td>
<?php
if($row4['country_name']=="INDIA")
{?>
<td id="statediv"><select name="state_id" class="medforminput" id="state_id" onchange="getCity('select_city.php?state_id='+this.value)">
<option value="">Choose State</option>
</select></td>
<?php else {
<td id="statediv"><input type="text" name="state_id" class="medforminput" id="state_id"/>
</td>
<?php }?>
</tr>
I am getting nothing what wrong in the concept?
I want to display select tag where user choose the "INDIA" else text box to enter the state.
You need to write an onChange event handler in javascript that tests the option selected, then either displays the dropdown or textbox in a dynamic div.
I'm going to use jQuery because it's a LOT less code.
Example:
<select name="country_id" class="medforminput" id="country_id" >
<!-- options go here -->
</select>
<script language="javascript">
$("#country_id").change(function() {
if ($(this).val() == 'India') { // put the country id here instead of string comparison
$("#stateInput").html(getStates());
} else {
$("#stateInput").html("<input type='text' id='stateId' name='stateId' />");
}
});
</script>
Please excuse the pseudocode - I didn't want to make it excessively long.

Update Price based on dropdown list selection

I have a dropdown list populated by mysql working perfectly, I also have it displaying the price set by mysql, so far i'm happy.
What the issue is as it's a multiple dropdown list, it will only display what is chosen first, if I pick 2 or more selections, only the first price is shown.
My second issue is I want the prices to add up i.e. 1st Selection's price is £1.99, 2nd Selection's price is £2.99 so the total should be £4.98
Finally once i have all this working, I want to continue this onto the 2nd / 3rd / 4th dropdown boxes so that all the boxes add up giving me a combined total.
Here's my html code to show you what i'm using:
<form method="post" action="" name="form1">
<?
include 'classes.php';
$query="SELECT * FROM Sex_Table";
$result=mysql_query($query);
?>
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()">
<option>Select Colour Type</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['ID']?> sex_price="<?=$row['Price']?>"><?=$row['Sex_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select><br /><br />
<p id="Clothingdiv">
<select style="width: 300px;" name="Clothing" disabled='disabled'>
<option>Select Sex First</option>
</select>
</p><br />
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true}); </script>
</form>
and here's my js:
function changePrice() {
var sex_price = $("option:selected").attr("sex_price");
$("#price_div").html("Price = £" + sex_price);
}
Thanks
Below is an example of what you're trying to do, I've given each select element I want to calculate the total for a class so that they are not mixed up with other elements.
jQuery
<script>
$(document).ready(function() {
$('.calculate').change(function() {
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});
</script>
HTML
<select class="calculate" name="select-1">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-2">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-3">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<span id="total">£0</span>
This will update the contents of total with the total price of each select element with class calculate when one of them is changed.
select with multiple should have the size attribute set as well, like this:
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple="multiple" tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()" size="10">
Your jQuery script:
$('select#Sexdiv').change(function() {
var value = 0;
$("select#Sexdiv option:selected").each(function(){
value += parseFloat($(this).val());
});
$("#price_div").html("Price = £" + value);
});
Hmm?

Categories