Iterate through my sql result and display in a loop - javascript

I am trying to get the result from "headline" and "content" to show up one at a time and then fade in and out to the next result in a loop. Currently, it shows all the results at once and the fades in and out and then show all the results again. Any idea on how to get them to show one at a time TIA
<html>
<head>
<style>
#table1{/*table aspects and design */
border:1px solid #FFFFFF;
background:#FFFFFF;
display:none;
width: 60%;
margin-left: auto;
margin-right: auto;
}
th{/*align table headers*/
text-align:center;
}
td,th{
border:1px solid #FFFFFF;
text-align:center;
}
</style>
</head>
<table id="table1" cellpadding="5" cellspacing="1" width="50%">
<? if ($query=$pdo->prepare("SELECT * FROM `Announcements_Current`"))
{
/* select all information from the table and take it into the page */
$query->execute();
while ($result = $query->fetch(PDO::FETCH_ASSOC)){
$head = $result['headline'];/*puts result of headline from table into variable*/
$content = $result['content'];
/*puts result of content from table into variable*/
echo /* echo the table to display announcements*/'
<tr>
<th>
<h1>
'.$head.'
</h1>
</th>
</tr>
<tr>
<td>
<font size="4">
'.$content.'
</font>
</td>
</tr>';
}
}
?>
</table> <!--end of table-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
/* define script for jquery*/
for (var i = 0; i < 500; i++) {/* for loop to fade in and out the announcements*/
$(document).ready(function() {/*function to fade table in and out*/
$('#table1').fadeIn(2000);
$('#table1').delay(5000);
$('#table1').fadeOut(2000);
}
)};
</script>

You're going about this the wrong way.
This won't be a complete solution. I'll try to hopefully make you understand the logic behind doing this yourself.
Loop through the results but instead of echoing them immediately, save them in arrays:
<?php
$head[] = $result['headline'];
$content[] = $result['content'];
?>
After the loop, only echo the first results. Add some IDs to your <h1> and <td> while you're at it. You'll need them later.
Then pass the arrays to JavaScript:
<script type="text/javascript">
var head = '<?= json_encode($head); ?>';
var content = '<?= json_encode($content); ?>';
</script>
Now that you have the arrays in JS, you have to iterate through them and for each value, change the content of your <h1> and <td>:
for (var i = 0, len = head.length; i < len; i++)
{
document.getElementById("H1_element_ID").innerHTML = head[i];
document.getElementById("TD_element_ID").innerHTML = content[i];
}
You can probably throw your fadeIn(), delay() and fadeOut() in this loop, to achieve your desired result!
Finally, delete your for and put this one inside $(document).ready().

Related

Save content editable HTML table in multiple fields

I need to develop a HTML table where one of the table column is editable on its row and the table row is dynamic in term of the row number.
I come across a problem where when I automate the saveEdits() function, the code is not working.
Here is my code, where the 'cnt' is a dynamic numeric number. Example cnt=50
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
table ,tr td{
border:1px solid #dddddd;
padding: 8px;
}
tbody {
display:block;
height:600px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
thead {
width: calc( 100% - 1em )
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script type="text/javascript">
function saveEdits(cnt) {
//get the editable elements.
var str_out = ''
while (cnt>0){
str1 = '\'edit' + cnt + '\': document.getElementById(\'edit' + cnt + '\').innerHTML,\n'
str_out = str_out.concat(' ', str1);
cnt--;
};
var editElems= { str_out };
alert(editElems)
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
function checkEdits(){
//find out if the user has previously saved edits
var userEdits = localStorage.getItem('userEdits');
alert(userEdits) // suppose to print {"edit1":" rpeyy7<br>","edit2":" tpruiiy<br>","edit3":" opty<br>"}
if(userEdits){
userEdits = JSON.parse(userEdits);
for(var elementId in userEdits){
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
</script>
</head>
<body onload="checkEdits()">
<table id="myTable">
<thead>
<tr>
<td style="background-color:#A9A9A9" > Field#1 </td>
<td style="background-color:#A9A9A9" > Field#2 </td>
<td style="background-color:#A9A9A9" > Field#3- Each Row Under field#3 is content EditableByUser </td>
</tr>
</thead>
<tbody>
// Here is the python code that loop through a diectionary content
cnt = 0
for c in sorted(data_dict.keys()) :
cnt += 1
<tr>
<td> {0} </td> //Field#1
<td> {0} </td> //Field#2
...
...
<td id="edit{0}" contenteditable="true" onKeyUp="saveEdits({0});"> {1} </td>\n'.format(cnt,comment)]
</tr>
</table>
</body>
I'm not sure where goes wrong as when I automate the saveEdits() function with 'cnt' in while loop, the above code doesn't works for me. But when I defined each row clearly like below, the data the keyed-in are properly saved to each column.
function saveEdits(cnt) {
//get the editable elements.
var editElems = {
'edit1': document.getElementById('edit1').innerHTML,
'edit2': document.getElementById('edit2').innerHTML,
'edit3': document.getElementById('edit3').innerHTML,
};
alert(editElems) //print [object Object]
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
I would be much appreciate if someone can point out my mistake. The error is very much likely on saveEdits(cnt) function but I'm not sure how to fix that cause it I define each count 1 by 1, each update that being keyed-in is actually saved properly and able to retrieve when rerun. Thanks you!

Can't get the numeric value from HTML using parseInt or Number in my js function

So I'm trying to complete this simple html page for a friend's project, the goal is to get 2 user entries, minutes and seconds, that will be compared to the data already in the table and if the minutes and seconds entered are greater than one of the time in the table, it will be replaced by the entry.
I've never worked with js except to make some simple prompt or alert so I don't know what I'm supposed to do.
Here is the html, js and css :
function timeEntry() {
var min1 = Number(document.getElementById('firstTimeMin'));
var sec1 = Number(document.getElementById('firstTimeSec'));
var min2 = Number(document.getElementById('secondTimeMin'));
var sec2 = Number(document.getElementById('secondTimeSec'));
var min3 = Number(document.getElementById('thirdTimeMin'));
var sec3 = Number(document.getElementById('thirdTimeSec'));
var entryMin = Number(prompt('What is the time in minutes ?'));
var newTimeMin = entryMin;
var entrySec = Number(prompt('What is the time in seconds'));
var newTimeSec = entrySec;
for (var i = 0; i < 3; i++) {
if (entryMin > min1 && entrySec > sec1) {
document.getElementById('firstTimeMin').innerHTML = newTimeMin;
document.getElementById('firstTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min2 && entrySec > sec2) {
document.getElementById('secondTimeMin').innerHTML = newTimeMin;
document.getElementById('secondTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min3 && entrySec > sec3) {
document.getElementById('thirdTimeMin').innerHTML = newTimeMin;
document.getElementById('thirdTimeSec').innerHTML = newTimeSec;
break;
}
};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
section {
width: 100%;
height: 100%;
}
table,
td {
width: 40%;
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
button {
cursor: pointer;
font-weight: 700;
}
<!DOCTYPE html>
<html>
<head>
<title>Table of best times</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="javascript/besttime.js"></script>
</head>
<body>
<section>
<table>
<tbody>
<caption>The best times</caption>
<tr>
<td id="firstTimeMin">1</td>
<td id="firstTimeSec">2</td>
</tr>
<tr>
<td id="secondTimeMin">3</td>
<td id="secondTimeSec">4</td>
</tr>
<tr>
<td id="thirdTimeMin">5</td>
<td id="thirdTimeSec">6</td>
</tr>
</tbody>
</table>
<button onclick="timeEntry()">
Enter a new time
</button>
</section>
</body>
</html>
My idea was to simply get the data already in the table using Number or parseInt to get the number value, but either way from the test I've been doing, when I try to get the element from html, it tells me that I get a number type but when I try to use it in an operation it returns NaN. Maybe I'm just stupid, but I've been reading and looking for a day for a way to get the data from the cells as numbers, but aside from Number or parseInt or using a form, I haven't seen a way to do this and it feels like the more I search the less I understand why it doesn't work.
Any help or clue on how to get this done, even it means start back from scratch would be really appreciated.
document.getElementById('firstTimeMin') only get the DOM Element, you should do document.getElementById('firstTimeMin').innerHTML to get the content of the HTML so you'll be able to get the number using parseInt() or Number.
Do the same with every elements.

Change DIV color checkbox onclick IN LOOP

I have searched for several hours now trying to implent scripts to change the div background. I've found this solution which works when it's not in a loop:
Javascript: onClick checkbox change div color
The challenge here is that the checkboxes is in a foreach loop with unique id values.
Here is my code:
<script language="JavaScript" type="text/JavaScript">
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#0000FF';
} else {
x.style.backgroundColor = '#FF0000';
}
}
</script>
<style type="text/css">
#result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
</style>
</head>
<body>
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div id="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(result, this)">
</div>
<?php } ?>
With this code it will show all the rows which are selected from the tabel but it won't change the div color when clicking the checkbox.
Help is very much appreciated. :-)
You're using the same id result to wrap all your checkbox elements. ids should be unique, use class="result" instead to wrap your checkbox elements. Plus, you don't have to send anything except this to myFunction function. So change your code in the following way,
CSS
.result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
PHP
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div class="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(this)">
</div>
<?php
}
?>
JavaScript
function myFunction(_this) {
if (_this.checked) {
_this.parentElement.style.backgroundColor = '#0000FF';
} else {
_this.parentElement.style.backgroundColor = '#FF0000';
}
}
The problem with your code is that line: onChange="myFunction(result, this)".
At that line result is not defined, usually it is common to pass a string with selector, or string with an id.
Something like that onChange="myFunction('result', this)"
And then in you JS function use document.getElementById to get a reference to the DOM element.
<script language="JavaScript" type="text/JavaScript">
function myFunction(id, _this) {
if (_this.checked) {
document.getElementById(id).style.backgroundColor = '#0000FF';
} else {
document.getElementById(id).style.backgroundColor = '#FF0000';
}
}
</script>

Auto-Suggest Text Box

I found an example online that shows how to build a auto-suggest text field by using javascript and PHP. Originally I started out by building my on version of the example, but after many failed attempts in getting it to work, I decided to see if the example itself even worked. I copied and pasted the example, changing only the database connection and the information regarding the database table. To my surprise the example still doesn't work! In my database I have a a table called Device and in that table there are three columns, ID,Device_type, and Price. Right now I have one value in the table and it's Apple iPhone 6 in the Device_type column, so when the program is working correctly, it should start to auto suggest Apple iPhone 6 as soon as I type "A" into the text box. Unfortunately, that doesn't happen, a dropdown box appears, as it should, but the box is blank and doesn't show any suggestions.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Suggestion Example</title>
<style type="text/css">
<!--
div.suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
text-align: left;
}
-->
</style>
<script type="text/javascript">
var nameArray = null;
</script>
</head>
<body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">
<?php
mysql_connect("hostname", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DeviceRecycling');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo("<script type='text/javascript'>");
echo("this.nameArray = new Array();");
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
<!-- --------------------- Input Box --------------------- -->
<table border="0" cellpadding="0" width="50%" align="center">
<tbody align="center">
<tr align="center">
<td align="left">
<input type="text" id="txtSearch" name="txtSearch" value="" style="width: 50%; margin-top: 150px; background-color: purple; color: white; height: 50px; padding-left: 10px; padding-right: 5px; font-size: larger;" onkeyup="doSuggestionBox(this.value);" />
<input type="button" value="Google It!" name="btnGoogleIt" style="margin-top: 150px; background-color: purple; color: white; height: 50px; font-size: larger;" onclick="window.location='http://www.google.com/#hl=en&source=hp&q=' + document.getElementById('txtSearch').value" />
</td>
</tr>
<tr align="center">
<td align="left">
<div class="suggestions" id="divSuggestions" style="visibility: hidden; width: 50%; margin-top: -1px; background-color: purple; color: white; height: 250px; padding-left: 10px; padding-right: 5px; font-size: larger;" >
</div>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
var input = text; // store inputed text as variable for later manipulation
// determine whether to display suggestion box or not
if (input == "") {
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
} else {
document.getElementById('divSuggestions').style.visibility = 'visible'; // shows the suggestion box
doSuggestions(text);
}
}
function outClick() {
document.getElementById('divSuggestions').style.visibility = 'hidden';
}
function doSelection(text) {
var selection = text;
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
document.getElementById("txtSearch").value = selection;
}
function changeBG(obj) {
element = document.getElementById(obj);
oldColor = element.style.backgroundColor;
if (oldColor == "purple" || oldColor == "") {
element.style.background = "white";
element.style.color = "purple";
element.style.cursor = "pointer";
} else {
element.style.background = "purple";
element.style.color = "white";
element.style.cursor = "default";
}
}
function doSuggestions(text) {
var input = text;
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
</script>
</body>
</html>
In my attempt to trouble shoot, I have discovered a few things. First off the connection string to the database is good, and that is not the problem. In an attempt to further check whether it was the database query that was causing issues, I have discovered that if I remove the echo("<script type='text/javascript'>") from the PHP portion of the code, that it will actually print Apple iPhone 6 at the top of the page, which tells me the query itself is actually working. Obviously though, by removing the javascript tag the program still doesn't work because it should only be displaying the results as you type something that matches what is in the database.
hi maybe you have a error on your code
this is a little example
for get the result and show
autocomplete.php
<?php
$connection = mysqli_connect("localhost","username","password","employee") or die("Error " . mysqli_error($connection));
//fetch department names from the department table
$sql = "select department_name from department";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['department_name'];
}
echo json_encode($dname_list);
?>
for view and show the result
demo.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<!-- load jquery ui css-->
<link href="path/to/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<!-- load jquery library -->
<script src="path/to/jquery-1.10.2.js"></script>
<!-- load jquery ui js file -->
<script src="path/to/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#department_name").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="department_name" type="text" size="50" />
</body>
</html>
i preffer use jquery
donwload jquery
enter link description here
result

JavaScript how to get this html to read this CSS and organise my script into the table

How it looks:
How I want it to look:
I have a CSS file that has a table all organised and ready my question is how do I get my script to use the table in the CSS file this is my CSS file:
/*
styles.css
*/
body{
background-color:#cecece;
color:#fff;
font-family: Arial, Tahoma, Sans-Serif;
font-size:1em;
}
h1{
color:#FF8000;
text-align:center;
}
table{
width:95%;
}
caption{
font-size:1.2em;
margin:10px;
color:#FF8000;
}
th{
width:33.333%;
font-size:1.1em;
text-align:left;
color:steelblue;
}
#output{
position:absolute;
width:50%;
height:70%;
top:15%;
left:25%;
margin:0px;
padding:10px;
font-size:.9em;
background-color:#2E2E2E;
color:ivory;
}
this is my Html document that calls the css and my script
<html lang="en">
<head>
<title>Student Grades - [Your Name]</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<h1>Student Grades System</h1>
<div id="output"></div>
<script src="./assignment.js"></script>
</body>
</html>
This is my JavaScript that prints everything out if u need more of the script let me know
var mytable = "<table><caption>Grading Results</caption>";
document.write(mytable);
document.write('<td><tr><th>' + "Student"+'</th><th>' + "Mark!" + '</th><th>'+"Grade" + '</th> </tr></td>');
for(var i = 0; i < markArr.length; i++){
document.write(' <tr><td>'+studentArr[i] + space1+markArr[i] + space1+gradeAwarded[i] + '</td> </th> ');
}
document.write(' </tr>');
document.write('<td>'+ "The Highest mark was : "+max+ ''+'</td> </th>');
document.write('<td>' + "The Lowest mark was : "+min+''+'</td> </th>');
document.write('<td>'+ "The Average mark was : "+average+''+'</td> </th>');
document.write('<td>' + "number A grades : "+A+''+'</td> </th>');
document.write('<td>'+ "number B grades : "+B+''+'</td> </th>');
document.write('<td>'+ "number C grades : "+C+''+'</td> </th>');
document.write('<td>'+ "number F grades : "+F+''+'</td> </th>');
document.write('</table>');
Try this
Add the code below before the for loop:
document.write('<table><caption>My Caption</caption>');
and this after the loop:
document.write('</table>');
The problem you told me happened because the <div> was closed before the <table> was created. Try this:
<div id="output">
<script src="./assignment.js"></script>
</div>
together with my code above.
Hope it works!
A HTML table generally has the format
<table>
<tr>
<th>Header1</th>
<th>Header2</th>
</tr>
<tr>
<td>Item1Row1</td>
<td>Item1Row2</td>
</tr>
<tr>
<td>Item2Row1</td>
<td>Item2Row2</td>
</tr>
</table>
Try creating a variable and build the html object as a string, then adding it to a element.
something like this:
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr></table>";
document.getElementById('body').innerHTML = myTable
Try this
Add the code below before the for loop:
var mytable = "<table><caption>My Caption</caption>";
and this after the loop:
document.write(mytable +'</table>');
#HelloWorld, here you go. Click on CSS and JavaScript tabs to see how I set it up
http://jsbin.com/cogux/1/edit?html,output
Without knowing what assignment.js does, the main steps would be:
Create/compile a data set you can loop through
Dynamically create the table rows and data
Create the statistics area for top student, marks and number of grades (just refer to how I set up #2)
Insert table into a target element. In the case for #2 the target was the <tbody> element
I hope this helps.

Categories