Show table data on another page in a table HTML - javascript

My problem is the following:
I have created an array from a table I already have and stored the column I want into an array, and then stored it in the localStorage using JSON.stringify:
function createArray(){
var arrayPlayerName = [];
var count = 1;
while(count<=playerNum){
arrayPlayerName.push(document.getElementById('playertable').rows[count].cells[1].innerHTML);
count++;
}
localStorage.setItem("playerNameArray", JSON.stringify("arrayPlayerName"));
}
(playerNum is a variable with a fixed number used in other methods, and the "getElementById" works).
After that I want to show this data in another table in another HTML doc.
So, the following is my HTML code:
<table class="myTable">
<thead>
<tr class="row">
<th colspan="3">Array List</th>
</tr>
</thead>
</table>
And this is the script:
var storedPlayerArray = JSON.parse(localStorage.getItem("playerNameArray"));
tablegenerate (storedPlayerArray);
function tablegenerate (list) {
for(i=0; i<playerNum;i++){
var $formrow = '<tr><td>'+list[i]+'</td></tr>';
$('.myTable').append($formrow);
}
}
I am not sure what I'm doing wrong.. thanks in advance.
EDIT: I am calling the createArray function with a button, and I'm navigating to the second page with another button. The second page should load directly.
EDIT2: I have revised that the array is being stored and called properly on the second page, so the issue is now on the "tablegenerate" function.

EDIT
I think I found the problem try this:
var storedPlayerArray = JSON.parse(localStorage.getItem("playerNameArray"));
function tablegenerate (list) {
for(var i=0; i<list.length;i++){
var $formrow = $('<tr><td>'+list[i]+'</td></tr>');
$('.myTable').append($formrow);
}
}
$(document).ready(function(){
tablegenerate (storedPlayerArray);
})
You have an issue in your createArray function.. You are running JSON.stringify on a string instead of the array you want to store.
Change this:
localStorage.setItem("playerNameArray", JSON.stringify("arrayPlayerName"));
To this:
localStorage.setItem("playerNameArray", JSON.stringify(arrayPlayerName));

Related

Using 'onload' alike function for td element

I have a datatable in my django template, I have a td element in the table as shown below
<td onclick="setColor('{{x.name}}')">{{x.name}}</td>`
I need this element to run the function 'setColor' everytime the webpage is loaded. I am unable to use onload here as oload is not valid for such elements, but I need to pass those parameters(because I am using a for loop here and this function gets called mutliple times in the loop with different {{x.id}}) which restricts me to only call this function from the exact td element. Is there a way that I could achieve this, so that the function gets called when the page loads and also the parameters are passed to the function?
I have used django filter to solve this issue. The html code is given below:
{% load filters.py %}
<td><span style="color:{{x.name|getNameColor}}">{{x.name}}</span></td>
I defined the getNameColor filter in my filters.py as shown below:
#register.filter(name='getNameColor')
def getNameColor(value):
if value == 'xxx':
return '#f19203'
elif value == 'yyy':
return '#b3a800'
elif value == 'zzz':
return '#f45c42'
elif value == 'uuu':
return '#44cc00'
Useful link: http://www.pfinn.net/custom-django-filter-tutorial.html
For who is searching a HTML/Javascript answer:
I had the same problem and found the solution in using custom attributes that I retrieve in the window.onload function. In my page I used the <tr> element, but this should work for a <td> also.
In the table:
<table>
<tr name="my_row" foo="value1"><td>value1</td></tr>
<tr name="my_row" foo="value2"><td>value2</td></tr>
</table>
In the window.onload function:
window.onload = function bar() {
var rows = document.getElementsByName("my_row")
for (row in rows) {
var foo = row.getAttribute("foo")
if (foo == "value1") {
// Do something
}
}
}

Delete multiple rows of Table in AngularJS

I have angularjs table added with check boxes to each row and a common remove button outside the table, so that multiple rows can be selected and deleted at a time. When rows are selected and remove is clicked, that particular rows will be deleted. This is fine and till here its working in the below plunker too. Now what I need is when a particular row is selected, its rowid has to be sent as a parameter to another URL. when this URL(URL formed by selected rowIds) with ids is called, automatically the rows will be deleted from first URL data, and now the table has to be updated from first URL. null will be returned from second url with ids as parameters and at the same time that rows will be deleted from JSON data of first URL.
Here is a demo:http://plnkr.co/edit/UzKdIGSubEfHoF7FHoCd?p=preview
Below is the code for the table:
<div ng-controller="SampleController">
<form class="form-horizontal">
<a class="btn btn-info" ng-click="subt_click()">Submit</a>
</form>
<div class="table-responsive" ng-show="tableData.length > 0">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th><input name="all" type="checkbox" ng-click="selectAllFriends()" /></th>
<th>ID</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableData">
<td><input name="all" type="checkbox" ng-model="x.checked" /></td>
<td>{{x.id}}</td>
<td>{{x.body}}</td>
</tr>
</tbody>
</table>
</div>
<input ng-hide="!tableData.length" type="button" class="btn btn-danger pull-left" ng-click="remove()" value="Remove">
app.js:
$scope.remove = function () {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.tableData, function (checked) {
if (!checked.checked) {
newDataList.push(checked);
}
});
$scope.tableData = newDataList;
};
$scope.isAll = false;
$scope.selectAllFriends = function () {
if ($scope.isAll === false) {
angular.forEach($scope.tableData, function (x) {
x.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.tableData, function (x) {
x.checked = false;
});
$scope.isAll = false;
}
};
In brief what i need is:
I get table data from first url. (pls check the plunk and the url i used is jsonplaceholder.typicode.com/posts)
When a checkbox is selected from a row in table and remove button is clicked, that rowid has to be sent to second URL(need to call another url, need not post) and this url when called along with selected rowids deletes that particular row details from first url and returns a null.
Finally, the first url data(which will be modified by just calling second url with rowids) has to be updated in the table present already.
How can I change this code to send rowid to second url and call that url to update the table. Thanks in advance!!
$scope.xListNo is never affected in your statements.
May be you wanted to use xListNo which is your function parameter (without $scope) ?
So does index in your second statement, which should be idx.
Double check your variables spelling and it should work !
#Deborah : Went through your Plunker and could not find any code for Posting ids to an URL. Assuming that you are doing that somewhere, Still there can be two cases, whether to remove data as soon as call is made or removing it after response from API call. The better way would be removing after the success of API.
So, what you should do probably is to keep your entire table data in a variable (as you have already done, after your GET call).
//Table Data
$http.get("http://jsonplaceholder.typicode.com/posts")
.success( function(response) {
$scope.tableData = response;
});
Now In remove function you can create an array of rows which are checked and send them to URL..Like:
$scope.remove = function(){
$scope.deletedIds = [];
$scope.tableData.forEach(function(x){
if(x.checked){
$scope.deletedIds.push(x)
}
}
makePostCallFOrDeletion()
}
//use this if POST call
function makePostCallFOrDeletion(){
$http.post("deleteurl", angular.toJson($scope.deleteIds)).then(function(response){
$scope.tableData = response //assuming you get the updated JSON back.
//if you don't get JSON back, delete yourself from JSON, like
$scope.tableData.forEach(function(x,i){
if ($scope.deleteIds.indexOf(x.id) !== -1)
$scope.tableData.splice(i, 1);
}
}
As per my understanding of your question, this should get you going..
EDIT: OP wanted GET call for deleting (which as per my opinion is not a good idea, since number of IDs can be too large)
//use this if GET call
function makePostCallFOrDeletion(){
$http.get("deleteurl" + append IDs here,).then(function(response){
//$scope.tableData = response //assuming you get the updated JSON back.
//if you don't get JSON back, delete yourself from JSON, like
$scope.tableData.forEach(function(x,i){
if ($scope.deleteIds.indexOf(x.id) !== -1)
$scope.tableData.splice(i, 1);
}
}

Manipulating images via javascript, very simple

edit:
thanks a lot ya'll. Have a great night/day
All I'm trying to do is have javascript change the image src in a table cell by checking the id of the cell.
I have looked at every single related question on stack overflow and their solution. For some reason, my code won't work. Most likely syntax/lack of sleep issue
This js script in a table, located right above the src I'm trying to change depending on things:
<script>
function getImage(){
return "http://i.imgur.com/s5WKBjy.png"; //i literally just want to see if this works and it isn't
}
document.onload = function(){
document.getElementById('homeimage').src = getImage();
};
</script>
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimage" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimage"></td>
neither of the above work. With the onload = "getImage()" and without. Am I being dumb? There's got to be something obvious I'm missing.
As if you don't want to use any ID the you can use this method,
This code works for n number td's in your table....
window.onload = function()
{
var rows = document.getElementsByTagName("table")[0].rows;
tds = rows[0].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
tds[n].getElementsByTagName('img')[0].src = getImage();
}
}
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
<table>
<tr>
<td colspan="3"><img style="width:110px;height:128px;"></td>
<td colspan = "3"><img style="width:150px;height:128px;"></td>
</tr>
</table>
You can't have two images with the same id. Name one homeimage1 and the other one homeimage2 for instance.
We can't use same id more than once in a single web page. Use different ids.
2nd change doucment.onload to window.onload
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
window.onload = function(){
document.getElementById('homeimageA').src = getImage();
document.getElementById('homeimageB').src = getImage();
}
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimageA" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimageB"></td>
Things to note:
You have duplicate IDs, where IDs are should be unique.
You should use encodeURIComponent() to return the url value.
You don't have to use onload on the image itself.
You should bind the onload event on window object, that will do.
Before set the src just decodeURIComponent() to return value.
<td colspan="3"><img style="width:110px;height:128px;" id="homeimage1"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id="homeimage2"></td>
Now changes in js:
<script>
function getImage(){
return encodeURIComponent("http://i.imgur.com/s5WKBjy.png"); //i literally just want to see if this works and it isn't
}
window.onload = function(){
document.getElementById('homeimage').src = decodeURIComponent(getImage());
};
</script>

How to automatically call a JavaScript that modify a value before show this value?

I am very new in JavaScript and I have the following problem to solve.
I have a table that contains this td cell:
<td class= "dateToConvert" width = "8.33%">
<%=salDettaglio.getDataCreazione() != null ? salDettaglio.getDataCreazione() : "" %>
</td>
This retrieve a String from an object and show it into the cell
The problem is the retrieved string represent a date having the following horrible form: 20131204 and I have to convert it into the following form: 2013-12-04.
So I am thinking to create a JavaScript that do this work when the value is retrieved.
My problem is: how can I do to automatically call the JavaScript before to show the value into the td cell? (So I show the modified output in the desidered form)
EDIT 1:
So I have create thid JavaScript function into my page:
function convertData() {
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.innerText = td.innerText.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
}
But it don't work because it never enter in this function (I see it using FireBug JavaScript debugger). Why? What am I missing? Maybe have I to call it explicitly in some way in my td cell?
Of course it is better to fix backend method to make it return proper format. But since you have no control over it try to use something like this:
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
Check the demo below.
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
<table>
<tr>
<td class= "dateToConvert" width = "8.33%">
20131204
</td>
<td class= "dateToConvert" width = "8.33%">
20140408
</td>
</tr>
</table>

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

Categories

Resources