Error JavaScrit code trying to live search a paginated table - javascript

I am trying to find one particular name and position, for someone listed in a paginated table with a webpage search bar. The code below is very simple league system. The data is ordered by profit desc. The position is calculated using row number and is then paginated.
So for example Page 1 will have the first 31 records, numbered 1-31, with the highest profit at position 1 next 2 and so on. Page 1 is labelled league 1. The next 31 records become league 2 again with the top profit in league 2 becoming position 1 ect.
Everything works fine apart from my search bar. What I am trying to do is enter a name in the search bar to find what league that person is in and what their position is. Ideally, the search result should show the page which the person is listed and somehow highlight that person. At the moment I am stuck on finding the name. The JavaScript at the bottom of the code, I thought should find the name and hide the rest but it does not. It works fine when using it on a basic hand coded html table. I would be grateful for any thoughts in pointing me in the right direction.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Sales League</title>
</head>
<body>
<?php
$con = mysqli_connect("localhost", "root","","salesleague");
$rpp = 31;
isset($_GET['page']) ? $page = $_GET['page'] : $page = 1;
if($page > 1){
$start = ($page * $rpp) - $rpp;
}else{
$start = 0;
}
$resultSet = $con->query("SELECT id from salesleague_march");
$numRows = $resultSet->num_rows;
if($resultSet->num_rows > 0){
$rowNumber=0;}
$totalPages = $numRows / $rpp;
$resultSet = $con->query("SELECT * FROM salesleague_march ORDER by Profit desc LIMIT $start, $rpp");
echo "<h1>Sales League $page </h1>" ;
echo "<table id='tabl1' border 1px >
<tr>
<th>Position</th>
<th>Name</th>
<th>Branch</th>
<th>Units</th>
<th>Profit</th>
</tr>";
while($rows = $resultSet->fetch_assoc()){
$rowNumber++;
$name = $rows['Name'];
$branch = $rows['Branch'];
$units = $rows['Units'];
$profit = number_format($rows['Profit']);
echo "<tr><td>$rowNumber</td><td>$name</td><td>$branch</td><td>$units</td><td>£ $profit</td></tr>";
}
echo "</table><p />";
for($x = 1; $x <= $totalPages + 1; $x++){
echo "<a href='?page=$x'>$x</a> ";
}
?>
<input type="text" id="Namesearch" placeholder="Salesperson Search"></input>
<script>
$("#Namesearch") .on("keyup", function()
{
var value=$(this) .val();
$ ("table tr") .each(function(records)
{
if(records !==0)
{
var id=$ (this) .find ("td:first") .text();
if(id.indexOf(value)!==0 && id.toLocaleLowerCase().indexOf(value.toLocaleLowerCase())<0)
{
$ (this) .hide();
}
else
{
$(this) .show ();
}
}
});
});
</script>
</body>
</html>

Related

Selecting a specific column in a option box using Javascript

I'm using the following php code to create a select option box:
$TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
while($Row = mysqli_fetch_array($TypeLU)) {
$TypeOptions = $TypeOptions."<option>$Row[1] $Row[2]</option>";
}
In HTML it gets displayed as a list with 2 columns. If I select and item from the list the value would be the concat of both $Row[1] and $Row[2] which is fine for display purposes, but I want to be able to 'extract' for example only $Row[1] as being the 'bound' value which I can then use as refrence.
So in pure Javascript I want to be able to get the value of just $Row[1] for example:
var x = document.getElementById("selectbox").value;
// So x must be only $Row[1] and not the concat of $Row[1] $Row[2]
Thanks
Use:
$TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";
You may also want to consider escaping the variables in case they contain any < or " or other special HTML characters. See htmlspecialchars.
Full example with escaping:
$TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
while($Row = mysqli_fetch_array($TypeLU))
{
$Row[1] = htmlspecialchars($Row[1]);
$Row[2] = htmlspecialchars($Row[2]);
$TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";
}

HTML form select to drive PHP/SQLSRV results

I'm working on a very basic web page to facilitate data entry. I have it working with PHP talking to SQL Server to both enter and display data. At the simplest level, they'll select a store from a dropdown and enter some data, then hit submit.
I'm trying to dynamically display the last 7 days worth of data when their store is chosen from the form select input. How do I get the Select value to drive the SQL query? I found how to use onchange to fire a javascript function, which I can alert the value. Do I really need to then use jquery or AJAX to link that back to the PHP select query or is there a simpler way to approach this?
I'm trying to learn this all from scratch and am quite admittedly out of my element. Here are some snippets of what I've got:
...
<script>
function OnSelectChange(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
</script>
...
<td align="right">Store</td><td width="125"><select style="width:100%" name="store" onchange="OnSelectChange(this)">
...
<?php
$tsql = "select * from test where DateStamp >= getdate()-7";
$stmt = sqlsrv_query($conn, $tsql);
//generate table view of data
echo "<table>";
echo "<tr><td>Store ID</td><td>Date</td><td>Data</td></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$StoreID = $row['StoreID'];
$DateStamp = $row['DateStamp'];
$Donations = $row['Data'];
echo "<tr><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
}
echo "</table>";
?>
I've found a lot of helpful information to get me this far, but am stuck now.
Thank you in advance.
Got it! For anyone else looking, here are relevant snippets of code:
<style>
.hideable {
visibility: collapse;
}
</style>
...
<script language="JavaScript">
function OnSelectChange(cl)
{
var els = document.getElementsByClassName('hideable');
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'collapse';
};
var els = document.getElementsByClassName(cl);
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'visible';
};
}
</script>
...
<select style="width:100%" name="store" onchange="OnSelectChange(this.value)">
...
echo "<tr class='hideable ".$StoreID."'><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
Leveraging dual classes upon the table (tr) creation and the collapse CSS style property was key.

remain the value of input after hide

I have an edit function where their is a function that has hide/show if i click edit. My problem is how can i remain the value of row if im going to hide it?
for example i have this dialog
and decided to edit sample 1(first row)
and then i decided i realize that i dont want to edit sample 1 then close it (by clicking edit again) then i want to edit sample 5 but i got this error
here is my script
//show and hide update button checker
function update_contain(){
var row = jQuery(".beneficiaries_rows input[type='text']:visible").length;
if(row > 0){
jQuery('.ui-dialog-buttonpane button:contains("Update")').button().show();
}else{
jQuery('.ui-dialog-buttonpane button:contains("Update")').button().hide();
}
}
//beneficiaries edit
jQuery(".edit_beneficiaries").click(function(){
var row = jQuery(this).closest(".beneficiaries_rows");
var show = row.find(".hide");
var hide = row.find(".show");
if(jQuery(show).is(":visible")){
jQuery(show).css({"display":"none"});
jQuery(hide).css({"display":"inline-block"});
}else{
jQuery(hide).css({"display":"none"});
jQuery(show).css({"display":"inline-block"});
}
update_contain();
});
HTML
<table style="border: 2px solid black;margin:auto;">
<tr>
<th style="width:145px;"><center>Name<center></th>
<th><center>Action</center></th>
</tr>
<?php
while($row1 = mysql_fetch_array($result1)){
echo "<tr class='beneficiaries_rows' id='".$row1['id']."' data-id='".$row1['ben_id']."'>";
echo "<td><input class='hide' type='text' name='bename_update' value='".$row1['name']."'></div>";
echo "<div class='show'>".$row1['name']."</td>";
echo "<td>";
echo "<center><button class='del_beneficiaries'>X</button><button class='edit_beneficiaries'>Edit</button></center>";
echo "</td>";
echo "</tr>";
}
?>
</table>
P.S im not good in english thats why im posting a picture to elaborate
my question
You'll want to set the text inside your label with something like this
jQuery("[selector for your label]").html(jQuery("[selector for input]").val());
I suggest doing this on click, just before you hide the input.
edit; since you're not really following:
jQuery(".edit_beneficiaries").click(function(){
var row_display = jQuery(this).parents("tr").find(".show");
var row_edit = jQuery(this).parents("tr").find(".hide");
jQuery(row_display).html(jQuery(row_edit).val());
});

Text not marking up

I am writing a page which allows a tournament director (TD) to add players to an event. When the TD goes to search for a player I want the search results to appear on keyup below the search input (without needing to refresh the page).
At this stage I have 2 php pages and 1 js page and have the live search happening, but the output is not getting marked up. I have written a piece of code to convert a PHP $_SESSION[''] array to a javascript array, but my brain is frying and I'm not sure where to go from here.
I effectively want the processed version of this code as output (presuming the SQL returns only 1 player named John Smith)
<tr></td> 123 </td><td> John Smith </td></tr>
My main php page has:
<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?></th></tr>
<tr><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th></tr>
<tr><td colspan='3'>Search <input type='text' id='newsearch'</input>
</table>
<br>
<div id="newsearch-data"> </div>
<script>
var players = [];
</script>
<?php
//Makes php array into js array
foreach ($_SESSION['players'] as $id){
echo "<script> players.push('" . $id . "') </script>";
}
?>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script>
<script src="global.js"> </script>
js page:
$('input#newsearch').on('keyup', function(){
var newsearch = $('input#newsearch').val();
if ($.trim(newsearch)!= "") {
$.post('newsearch.php', {newsearch: newsearch}, function(data) {
$('div#newsearch-data').text(data);
});
}
});
And 2nd php page
<?php
session_start();
unset($_SESSION['players']);
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';
$term = $_POST['newsearch'];
$terms = "%" . $term . "%";
$_SESSION['players'] = array();
$query = ("SELECT * FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
while ($dbsearch = mysqli_fetch_assoc($run_query))
{
array_push ($_SESSION['players'],$dbsearch['PlayerID']);
echo "<tr><td>" . $dbsearch['PlayerID'] . "</tr></td>";
}}?
How can I output a new row on a html table rather than raw html code?
replace $('div#newsearch-data').text(data);
with $('div#newsearch-data').html(data);
$.text() escapes the input string and you should use it when you know the input is a string, and that you want to preset it "as is". If the input includes actual HTML that you want to inject into the DOM, $.html() is your friend :-)
You need .html() to render output as a HTML rather than .text(), because .text() will output the result as a raw data, then try this solution instead :
$('div#newsearch-data').html(data);
Live example - credited to #Peter Bailey for live example.
References
http://api.jquery.com/html/ - .html()
http://api.jquery.com/text/ - .text()

how to display only 4 result in each page using html & sqlite

This is me once again as I got some error in previous question in the code. So asking this question once again.
This is code from phonegap app from index html page. I don't know how to get only 4 result from database at each page when a sqlite query processed?
Also I want to add next page button. When clicking on this button next 4 result from database should come. This is code.
function querySuccess(tx, results){
var len = results.rows.length;
var output = '';
for (var i=0; i<len; i++){
output = output + '<li id="' + results.rows.item(i).id + '">' + results.rows.item(i).list_action + '</li>';
}
messageElement.html('<p>There are ' + len + ' items in your list:</p>');
listElement.html('<ul>' + output + '</ul>');
}
Dividng your solution into 3 phases
Phase 1: Using LIMIT Clause you can limit number of rows to be displayed
SELECT expressions FROM tables WHERE conditions ORDER BY expression [ ASC | DESC ] LIMIT number_rows OFFSET offset_value;
For Example:
SELECT employee_id, last_name, first_name
FROM employees
WHERE favorite_website = 'divyashah.in'
ORDER BY employee_id DESC
LIMIT 4;
Phase 2:
As the code provided by you is not efficient to explain but still... Now for your Next button
1) Fetch number of rows from your database table (mysql_num_rows).
2) Store that number in a Variable say 'a'.
3) Divide it(a) with 4 and store it in variable 'b'.
4) Use if > if(b!=0) {display next button} else {no need to display}
Phase 3:
This will fetch your first four rows i.e. from 0 to 4.
<?PHP
$fetch = mysql_query("SELECT * FROM table LIMIT 0, 4")or
die(mysql_error());
?>
Now how can you make the next page show the next 4 records?
you simply have to store the value of the starting row in a variable and pass it in the URL as a GET variable. Also have to check if there was a value already passed or not so we can set a default value in case it wasn't (zero to start from first row):
<?PHP
//check if the starting row variable was passed in URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
?>
Now your query should have this new variable ($startrow) in the LIMIT clause
<?PHP
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM table LIMIT $startrow, 4")or
die(mysql_error());
?>
Now to see the next 4 records you should have a link which will add 4 to $startrow so you can view the next 4 records
<?PHP
//now this is the link..
echo 'Next';
?>

Categories