Dynamically Modifying Incountable Cells on Textbox Change - javascript

I have a table that creates new rows through PHP in regard to a database table that gets updated. Each row contains a unique class "rdClass" with an additional number that is incremented by a counter. A textbox is contained within each row with a unique id "workhr" with an additional number that is incremented as well. (rdClass0, ..., rdClass[n] ---------- workhr0, ..., workhr[n])
<td class='rdClass" . $counter . "'><input id='workhr" . $counter ."' name='HrsInShift" . $counter . "'></td>
What I'm trying to do is change the background color of rdClass# whenever the value in textbox workhr# changes respectively. I've already created a nice script in JQuery but it's not dynamic.
$(function() {
content = $('#workhr0').val();
$('#workhr0').keyup(function() {
if ($('#workhr0').val() != content) {
content = $('#workhr0').val();
$('.rdClass0').css("background-color", "blue");
}
else
$('.rdClass0').css("background-color", "");
});
});
How could I make this dynamic so that it detects value change for all workhr[n] and modify their rdClass[n] background colors respectively?

var dynamic_val;
$('[id^=workhr]').keyup(function(){
if($(this).val() != dynamic_val){
dynamic_val = $(this).val();
$('.rdClass'+$(this).prop('id').split('workhr')[1]).css('background-color', 'blue');
}else{
$('.rdClass'+$(this).prop('id').split('workhr')[1]).css('background-color', 'inherit');
}
});

Related

Duplication of rows in Javascript Table

I am quite new to javascript and for some time now i cant figure a solution to a problem that i have on my own. The web application i am building is using javavascript and Firebase. I am creating a table that pulls some data from mysql and display them as a table in my website. The table consists of three columns ID,NAME, AND SURNAME.Along with that i am also creating a new column called Recipient that consists of buttons. The table looks like this:
I give a different value to each of the buttons, the value of each button is the number of the ID that is in the same row as the current button. For example the first button has a value = 2, the 3rd a value = 123. Al the buttons have an id = contact
The source code of the table is
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName`,`storagefolder` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table class=table table-condensed>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Recipient</th>
</tr>
</thead>";
while($record = mysql_fetch_array($clients)){
echo "<action=usersfiles.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<button value=".$record['ID']." id=contact>Folder Data</button>"." </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
When i click on a button from the table the application get the value of the corresponding button and store it in a variable, then it sends the variable to a function that will drug all the files from firebase database that are store in the folder with the same name as the variable, And then it will display them.
My firebase Database
So for example when I click on the button of the first column I will get the files that are stored in the folder with name 2 form firebase.database. The result of after I click the first button will be this:
My source code works fines as it gets the files from the corresponding folders from firebase.database. The problem that i have is when i dont refresh the page and i click a button again then the outpout will be the result of the previous button click plus the new one. For example if i dont refresh my page and i click the second button to get the files from the file from database with the name = 3 the outpout will be :
The outpout is a merging of all the results that i have oupouted so far. If i refresh my page and click on the second button now i will get the result i want which it is:
How can i edit my source code so the tables wont merge?
My source code is the follwing:
Source code of saving the value after button is clicked and passsing it to function:
var contactName; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contact"]').click(function() {
contactName = $(this).val(); //set var contactName to value of the pressed button
store(contactName);
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
Source code of function receiving the value and displays the corresponding file from firebase database:
function store(value){
var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref().child(`files/${value}/`);
var rowIndex = 1;
databaseRef.once('value',function(snapshot){
snapshot.forEach(function(childsnapshot) {
var childKey = childsnapshot.key;
var childData = childsnapshot.val();
//var urls = childData.url;
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var button = row.insertCell(2);
var itd = document.createElement('input');
itd.setAttribute("type","button");
itd.setAttribute("value","View");
itd.onclick=function () {
window.open(childData.url);
};
cellId.appendChild(document.createTextNode(childData.filename));
cellName.appendChild(document.createTextNode(childData.created));
button.appendChild(itd);
rowIndex = rowIndex+1;
//document.write(username);
})
});
}
Thanks in Regards
You only append data to the existing table, without ever removing existing rows in the table:
var row = tblUsers.insertRow(rowIndex);
You should make sure to remove all existing rows before adding the new one(s):
for (var i = tblUsers.rows.length; i >= 0; i--) {
tblUsers.deleteRow(i - 1);
}

change the div color when function called - jquery

here is the list of products are printed using while loop
while($rr = $retval->fetch_object()) {
$summery_return .= '<div class="w3-blue w3-card-4" style="font-size:18px;">';
$summery_return .= '<span style="color:white;padding:2px;font-weight:bold" id="itmslct" data-proname='.$rr->product.'>'.$rr->product.'<span style="float:right;margin-right:19px;">'.$rr->qty.'</span>';
$summery_return .='</span><hr style="margin:3px"></div>';
}
script
$summery_return .='<script>
$(document).ready(function(){
$("#itmslct").click(function() {
var loc_proname = $(this).attr("data-proname");
alert(loc_proname);
$("."+loc_proname).css("background-color", "#f00");
});
});
</script>';
return $summery_return;
products in table
while($row = $result2->fetch_object()){
$icost=$row->quantity*$row->price;
$progress_return .='<tr class='.$row->product.'>
<td><b>'.$row->product.'</b></td>
<td><b>'.$row->type.'</b></td>
<td><b>'.$row->quantity.'</b></td>
<td><b>'.$row->pack.'</b></td>
<td><b>'.$row->topping.'</b></td>
<td><b>'.$row->extra.'</b></td>
<td><b>'.$row->comments.'</b></td>
<td><button style="background-color:red;color:white">Done</button></td>
</tr>';
$total=$total+$row->quantity*$row->price;
}
when i click on the product which is printed by first while loop then the background color of products in 2nd while loop should change.
There are multiple products in table with same name, all there background color need to be changed when i select the product on first while loop
i tried doing it but i don't see any results
I guess your code is not working because your HTML is not valid. In DOM; id should be unique. So to avoid duplicate ids; please modify PHP as well as corresponding JS code. Instead of id="itmslct" we will make it class as follows:
while($rr = $retval->fetch_object()) {
$summery_return .= '<div class="w3-blue w3-card-4" style="font-size:18px;">';
$summery_return .= '<span style="color:white;padding:2px;font-weight:bold" class="itmslct" data-proname='.$rr->product.'>'.$rr->product.'<span style="float:right;margin-right:19px;">'.$rr->qty.'</span>';
$summery_return .='</span><hr style="margin:3px"></div>';
}
And associated JS would be:
$(document).ready(function(){
$(".itmslct").click(function() {
var loc_proname = $(this).attr("data-proname");
alert(loc_proname);
$("."+loc_proname).css("background-color", "#f00");
});
});
ids should be unique. You should use a class instead.
Also, it appears you're setting the background color of a tr.
Try styling the td cells instead.
Either target them with the selector
$("."+loc_proname + ' td')
or add the class to the td elements.
I would recommend the second option as styling specific element selectors doesn't scale well in your styles.

RMarkdown: Color single cells in an HTML table based on conditions

I sucessfully generated a table in R markdown using xtable (HTML) .
Now I want to color format the 3rd column based on the values in the cell .
say highest value in red , lowest in green , and remaining in different shades.
The values in cell are generated dynamically . Some thing like this happens in excel quite easily using conditional formatting option . Can we do this in R using css ! Any help and suggestion welcome .. Thanks :)
You could use jQuery inside your RMarkdown script like this:
---
title: "Title"
author: "Yourname"
date: "June 16, 2016"
output: html_document
---
<script>
$(document).ready(function() {
$td = $('#myTable tr:not(:has(th)) :nth-child(5)');
var entries = new Array();
$td.each(function() {
entries.push(parseFloat($(this).html()));
})
var minimum = Math.min.apply(Math, entries);
var maximum = Math.max.apply(Math, entries);
$("#myTable tr :nth-child(5):contains('" + minimum + "')").css('background-color', 'green');
$("#myTable tr :nth-child(5):contains('" + maximum + "')").css('background-color', 'red');
});
</script>
```{r, echo=F, results='asis'}
library(xtable, quietly = T)
myTable <- xtable(head(mtcars))
print(myTable, type="html", html.table.attributes='border=1 id=myTable')
```
The JavaScript reads out all values of column 5 (:nth-child(5), including the row names) and checks for the minimum and maximum. Afterwards it matches the cells of that column with these values and applies CSS attributes.
Notice that I specified an ID for that table (#myTable). So if you have multiple table, the JavaScript can select the correct one.

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';
?>

Message always appears in first row?

I have a delete function within a function where if the user clicks on the "Delete" button, it displays a message stating that a file has been deleted. The code which does this is below:
$("#imagemsg").html(data);
But the problem is that let's say that I have 4 table rows and I delete a file in the 3rd row, the message should be displayed in the 3rd row only but instead it is displayed in the first row. Another example is that let's say that I have 8 table rows and I delete a file in the 6th row, the message should be displayed in the 6th row only but instead it is displayed in the first row.
Why is the message that is suppose to appear after a file is deleted is always displayed in the first row and not within the row the file has been deleted from?
Below is full code:
var counter = 0;
counter++;
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span id="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span id="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$("#imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
Below is the deleteimage.php script where the delete message is retrieved from:
<?php
$image_file_name = $_GET["imagefilename"];
echo "$image_file_name was Deleted";
unlink("ImagesFilesFolder/$image_file_name");
?>
The problem seems to be this:
.done(function(data) {
$("#imagemsg" + counter).html(data);
You set counter like this
var counter = 0;
counter++;
But you never seem to refer to the variable again. In any case, this variable is global - the command above will always target the ID with the current number of the counter, so it will not target the tr corresponding to the clicked button.
Since you use
$(this).parent().remove();
I assume that the parent is the tr concerned? In this case you could use a class instead of an ID 'imagemsg' and then do
$(this).parent().find(".imagemsg").html(data);
This would target the message inside the same row of the button.

Categories