I'm new to the jquery scripts, but I have an HTML table structured as follows inside my php code:
print <<<End_Of_HTML
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<thead>
<tr>
<th align="left" class="job_code">In/Out</th>
<th align="center">Time</th>
<th align="center">Date</th>
<th align="center" class="hrs" title="Regular work hours.">Hrs</th>$overtime_col$total_col
<th align="left" class="notes">Notes</th>
</tr>
</thead>
<tbody>
End_Of_HTML;
I then have a PHP-MySQL query populate that table with results and wanted to total up the hrs class based on the job_code classes value. I have this jquery script, which works on JSFiddle (http://jsfiddle.net/Lj6he/)
$(document).ready(function(){
var temp = [];
$('.job_code').each(function(index, element){
var text = $(this).text();
temp.push(text);
});
// remove duplicates
var job_code = [];
$.each(temp, function(index, element){
if($.inArray(element, job_code) === -1) job_code.push(element);
});
var sum = {};
$.each(job_code, function(index, element){
var total = 0;
$('.job_code:contains('+element+')').each(function(key, value){
total += parseInt($(this).next('td.hrs').text());
sum[index] = {'job_code' : element, 'total': total};
});
});
console.log(sum);
$.each(sum, function(index, element){
$('#total').append('<p>Total for '+element.job_code+': '+element.total+'</p>');
});
});
But when I enter it into my PHP file as follows it doesn't display what is seen on JSFiddle....any ideas are greatly appreciated. Thanks.
$PAGE_SCRIPT = <<<End_Of_HTML
<script type="text/javascript" src="scripts/jquery.totals.js"></script>
End_Of_HTML;
It just seems to not be displaying the results of the jquery on the page. Any ideas would be great.
Drop this line into the head section of your html output.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
that will import jQuery for you
ps, be sure to include it before any dependencies
You are appending your output to a non-existent element with id #total
Ensure the jquery library is referenced prior to your javascript code import.
The sample PHP code is missing
<div id="total">
</div>
This is the Div where the content is added.
Related
I am building a webpage to monitor my stocks and mark some comments for each stock.
I got the volume and the price of each of the stocks from an api I built and wrote some code to put them into a table.
The table has some other fields as well:
Name, Price, Volume, Comments, Target Price
The comments and target prices contain input fields which I can type in some notes for each stock.
However, my code builds a new table every 10s to update the stock prices and volume, and after each sort action which is triggered by pressing the corresponding heading I want to sort by. After this, my inputs fields contents will disappear. Is there a way to keep these contents intact after an update or a sorting is triggered?
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<table class="table table-striped" style="float: left; width: 60%">
<tr class="bg-primary">
<th data-column="name" data-order="dsc">Name ▲</th>
<th data-column="price" data-order="dsc">price ▲</th>
<th data-column="volume" data-order="dsc">Volume ▲</th>
<th data-column="targetPrice" data-order="dsc">Target Price ▲</th>
<th data-column="comments" data-order="dsc">Comments ▲</th>
<th data-column="submit" data-order="dsc">Send ▲</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var myArray = []
var sortOrder = 'name'
var sortColumn = 'dsc'
setInterval(function() {
$.ajax({
method:'GET',
url:'http://127.0.0.1:5000',
success:function(response){
myArray = response.data
if(sortOrder == 'dsc'){
myArray = myArray.sort((a,b) => a[sortColumn] > b[sortColumn] ? 1 : -1)
}else{
myArray = myArray.sort((a,b) => a[sortColumn] < b[sortColumn] ? 1 : -1)
}
buildTable(searchTable(myArray))
}
})
}, 10000)
function buildTable(data){
var table = document.getElementById('myTable')
table.innerHTML = ""
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].name}</td>
<td>${data[i].price}</td>
<td>${data[i].volume}</td>
<td><input type="number" name="${data[i].symbol}_targetPrice" style='width:60px;'></td>
<td><input type="number" name="${data[i].symbol}_comments" style='width:60px;'></td>
<td><input type="submit"></td>
</tr>`
table.innerHTML += row
}
}
</script>
The submit button is to send back the name, target price and comments as a dictionary back to the server, which I'm still figuring out how to do, however, the problem of the field contents disappearing is a much larger problem. Thanks in advance.
I think that your problem is in the UX more than in the code.
Re-building the HTML containing input elements every 10 seconds is a bad idea because:
You're going to lose focus of the input that you're typing in.
It's going to be overridden with the new data. (the problem you're facing)
It's confusing that inputs that you don't change get updated automatically.
To me it makes more sense to have a table with all the data (but no inputs), that can be updated every 10s. And an edit button that when is clicked shows a form with the inputs that won't update while you're typing.
I have a list of HTML tables given by pandas data frame in the format of:
list_html =
[<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>score</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.776959</td>
<td>grade</td>
<td>grade</td>
</tr>
<tr>
<th>1</th>
<td>0.414527</td>
<td>class</td>
<td>class</td>
</tr>, ... , ... ]
I am trying to visualize this data in an html page and could not do it. I do not have enough experience in web development. My goal is to use JavaScript to loop through each item the list and visualize them below each other in html. It would be great if anybody can help!
This is what I tried so far, its probably completely wrong:
var list_html = list_html // list of html codes as a javascript variable.
var arrayLength = analysis.length;
for (var i in list_html) {
document.getElementById("analysis_1").innerHTML = list_html[i];
}
Given a valid array of strings list_html (actually list_html is not a valid array of strings, since the markup in each entry is not wrapped in quotes) and a container in the DOM with id "analysis_1" it's simply a matter of:
var container = document.getElementById('analysis_1');
for (var i = 0; i < list_html.length; i++) {
container.innerHTML += list_html[i];
}
UPDATE:
well... in your scenario there is no need at all for a loop, you can simply inject a single string by joining the elements in the array:
document.getElementById('analysis_1').innerHTML = list_html.join('');
fast and simple! :)
using jquery's selectors :
Give the 'td' which contains the data a class name, eg: 'MyTd';
Select them all: $(.MyTd).text()
Done!
I'm trying to create a table with a JSON Object using Mustache.js.
I wanted it to show two rows, however it's only showing the second row only.
I suspect that the first row is being overwritten by the second when it's being bound again in the loop.
How do I work my way around it? Or is there a better structure I should follow?
Javascript:
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
Template :
<script id="user-template" type="text/template">
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</script>
table:
<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable">
</tr>
</table>
In additon to your own solution, you should consider using mustache to repeat the row for you:
<script id="user-template" type="text/template">
{{#people}}
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = {people: JSON.parse(text)};
$(document).ready(function() {
var template = $('#user-template').html();
var info = Mustache.render(template, obj);
$('#ModuleUserTable').html(info);
});
I figured out that instead of
$('#ModuleUserTable').html(info);
it should be :
$('#ModuleUserTable').append(info);
Template should be :
<script id="user-template" type="text/template">
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
</script>
and ID should not be on the table row tag. Instead it should be on the table itself:
<table border="1" id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
The moment when it appends, it adds a new row into the table with the JSON data.
I have the following html table
<table id="{64ED3A94-5833-4CC7-869F-CCE583B498BE}" class="ms-listviewtable"
width="100%" cellspacing="0" cellpadding="1" border="0"
xmlns:o="urn:schemas-microsoft-com:office:office" dir="none">
<tbody id="tbod23-1__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-2__" isloaded="true" style=""></tbody>
<tbody id="tbod23-3__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-4__" isloaded="true" style=""></tbody>
<tbody id="tbod23-5__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-6__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-7__" isloaded="true" style="display: none;"></tbody>
</table>
This table is autogenerated by a sharepoint xsltlistviewwebpart (didnt post in sharepoint as the question is more jquery+html related).
this is a treeview with nodes, when i expand a collapsed node it changes style from
style="display: none;"
to
style=""
The problem: the webpart does not remember which nodes were collapsed, so on each postback it resets all to expanded. What I need to do, is to remember the node state (expanded or collapsed) in a jquery cookie, and to retrieve it on postbacks (so, to persist the node state).
So far I got:
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("RememberClickedState");
function RememberClickedState()
{
var dv = $('.ms-listviewtable');
var items = [];
items = dv.find('tbody[id^="tbod"]');
$.cookie("itemListState", items);
alert(items[0]);
alert(items[1]);
}
</script>
Can anyone please provide some pointers on how to do this. Im a bit dazed and confused about the events themselves, on page_load I should save the cookie but also retrieve it somehow.
Also "items" array stored all 7 elements which is good, but when i try alert(items[0]); I get undefined.
Thank you
I suggest you to create string of this and then parse this string back... kind of like that:
var items = '';
function RememberClickedState() {
$('.ms-listviewtable tbody').each(function(){
tid = $(this).attr('id');
tvisible = $(this).is(':visible');
items += tid+':'+tvisible+','
})
//$.cookie("itemListState", items);
$('body').append(items+'<br/>');
}
function RestoreClickedState() {
//string = $.cookie("itemListState")
var string = items; //temporary
var cookies = string.split(',');
$.each(cookies, function(i, val){
val = val.split(':');
show = (val[1] == 'true' ? true:false);
item = $('.ms-listviewtable').find('#'+val[0]);
show ? item.show() : item.hide();
$('body').append('#'+val[0]+' is '+ 'display:'+show+'<br/>');
})
}
$(document).ready(function(){
RememberClickedState();
RestoreClickedState();
})
Here is DEMO:
http://jsfiddle.net/MYexv/3/
How can get a row's value on mouse click or checking the checkbox preferably from the below given html table?
Here is the js for getting values for my table from a xml using spry
var ds1 = new Spry.Data.XMLDataSet("xml/data.xml", "rows/row");
var pv1 = new Spry.Data.PagedView( ds1 ,{ pageSize: 10 , forceFullPages:true, useZeroBasedIndexes:true});
var pvInfo = pv1.getPagingInfo();
Here is the Div with spry region containing the table that gets populated from pv1 (see js part)
<div id="configDiv" name="config" style="width:100%;" spry:region="pv1">
<div spry:state="loading">Loading - Please stand by...</div>
<div spry:state="error">Oh crap, something went wrong!</div>
<div spry:state="ready">
<table id="tableDg" onclick="runEffect('Highlight', 'trEven', {duration: 1000, from: '#000000', to: '#805600', restoreColor: '#805600', toggle:true}, 'Flashes a color as the background of an HTML element.')"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="email"><b>Email</b></th>
</tr>
</thead>
<tbody spry:repeat="pv1">
<tr class="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
<tr class="trEven" name="trEven" id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying the below code but still I am not getting the alert and hence none of the answers are also not working. I know the syntax n all are everything correct, but i am not able to figure out what is the problem here!
//inside $(document).ready(function()
$("#chkbHead").click(function() {
alert("Hi");
});
My page has other tables too for aligning some contents. So when I use the below code it works perfectly on those tables except the one in the question. It might be the problem because there are only 2 tr in the table which gets populated by a spry dataset and hence not getting identified properly. May be, I am not sure, just trying to help improve my understanding
$('tr').click(function() {
alert("by");
});
The values of a Row you will get with:
$('#tableDg tbody tr').live( 'click', function (event) {
$(this).find('td').each( function( index, item ) {
if ( $(this).has(':checkbox') ) {
alert( $(this).find(':checkbox').val() );
} else {
alert( $(this).text() );
}
};
});
What exactly do you mean by value of a table row? You can get the inner html of a table row like this:
var html = '';
$('tr').click(function() {
html = $(this).html();
});
You can get attributes of the table row (e.g. it's Id) like so:
var id = '';
$('tr').click(function() {
id = $(this).attr('id');
});
Alternatively you can get the value of nested elements such as a text input like so:
var text = '';
$('tr').click(function() {
text = $(this).find('#myTextBox').val();
});
EDIT
This is how to change the checked attribute of a checkbox nested in a table row:
$('tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
EDIT
As the table rows are being loaded dynamically - the $().click() event binding method will not work, because when you are calling it - the table rows do not exist, so the click event cannot be bound to them. Instead of using $().click use the jQuery live method:
$('tr').live('click', function() {
// do stuff
});
This binds the click event to all current table rows and all table rows that may be added in the future. See the jQuery docs here
you have to use Spry Observer,
something like this:
function funcObserver(notificationState, notifier, data) {
var rgn = Spry.Data.getRegion('configDiv');
st = rgn.getState();
if (notificationState == "onPostUpdate" && st == 'ready') {
// HERE YOU CAN USE YOUR JQUERY CODE
$('#tableDg tbody tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
}
}
Spry.Data.Region.addObserver("configDiv", funcObserver);