I have a bunch of tr, that represent a cart
<tr class="cart_row">
<td>Product</td>
<td>£20</td>
<td>2</td>
</tr>
<tr class="cart_row">
<td>Product 2</td>
<td>£50</td>
<td>1</td>
</tr>
This gets updated via ajax when an item has been added.
What I'm looking to do, is to detect when the cart has been updated, i.e a new <tr> with a class of cart_rowor if the contents of an existing <tr> has been updated
Can I do this with jQuery?
Thanks
I would suggest this:
// a function to make a string out of thew data
function getData() {
var data = $('tr.cart_row td').map(function (el) {
return this.innerHTML;
}).get().toString();
return data;
}
//before the Ajax:
var valuesBefore = getData();
// do Ajax
//after the Ajax, ideally inside the callback (remeber ajax is async)
if (valuesBefore != getData()){ //do something };
Example
You can, with this:
$("#yourTable").on("DOMSubtreeModified", function() {
alert("table changed! row added");
});
See the browser support here: http://www.quirksmode.org/dom/events/#t18
EDIT However, it's getting deprecated
Hope this helps. Cheers
As far as I know, there is no event for this action. You should implement this with the help of setTimeout function. Set a function which checks if the count of needed elements changes.
Related
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));
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>
OK everybody, I hope you can help me. I have a problem with JQuery or better with the each selector of JQuery.
I have an example table, where I want to filter for special values which I entered before. Those values I got from my input field , store them in a variable, split the data an create an JQuery Object.
Well and then I think I have a problem with the selection, marked in the code section.
<p>
<input id="testyear" size="4" type="text">
<input value="Werte" onclick="getvalue()" type="button">
</p>
<script>
function getvalue() {
var wert = $('#testyear').val();
$("#years").find("tr").hide();
var data = this.value.split(" ");
// create jQuery Object
var jQueryObject = $("#years").find("tr");
// i think here is my error, i want to display only the object which are equal or better stored in my variable “wert”.
$.each(data, function (){
//jQueryObject = jQueryObject.filter(wert);
jQueryObject == wert;
});
jQueryObject.show();
};
<!--Example Table-->
<table id="years">
<tbody>
<tr>
<td>1997</td>
<td class="century">20</td>
</tr>
<tr>
<td>2001</td>
<td class="century">21</td>
</tr>
</tbody>
</table>
I expect, that when I enter 1997 in the inpt field, the whole tr which contains 1997 will be displayed. I know it is simple but I have no idea so thanks for your help.
Use a filter on the TR's after initially hiding them all.
e.g.
getvalue = function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
};
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/
Notes:
The ~~ is a little conversion to integer trick
You seem to have extra code you do not need in the example
Just get filter to return true for each item you want to keep and false for the rest
When using jQuery, avoid using inline event handlers (like onclick=). Use jQuery event handlers instead. See below:
e.g.
$('#wert').click(function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/1/
I think your problem is not in each() method (not selector). Your problem is here:
var data = this.value.split(" ");
this is not defined (you are not in an object scope). I think you need this:
var data = wert.split(" ");
-----------^^^^
You've obtain the value of wert in the last line.
In my Struts2 application, I have a table that is dynamically populated with data, coming from the database (via Eclipselink JPA). Below that table there's a button that became enabled as soon as a row is selected in the table (jQuery). Now, when that button is clicked, I need to know which row is currently selected, so I can access the corresponding object bean, since I need to pass the bean ID (target_id) into the next page (createexperiment2 action). So, in short, the question is: How can I access the Struts2 object bean that is contained in the selected (clicked) table row?
1. Screenshots:
Before row selection -> After row selection
2. JSP code:
<table id="targets" class="ink-table grey tableSection">
<thead>
<tr>
<th colspan="5" class="align-left">Select your target:</th>
</tr>
</thead>
<tbody>
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr id="row_<s:property value="i"/>">
<td class="all-100"><s:param name="id"><s:property value="target_id"/></s:param></s:url>"><s:property value="name"/></td>
<td class="all-15"><s:param name="id"><s:property value="target_id"/></s:param></s:url>">edit</td>
<td class="all-5">|</td>
<td class="all-15"><s:param name="id"><s:property value="target_id"/></s:param></s:url>">delete</td>
<td class="all-5">?</td>
</tr>
</s:iterator>
</s:if>
</tbody>
</table>
[...]
<a href="createexperiment2" class="ink-button double-vertical-space all-25 buttonSection" id="next" disabled>Next ></a>
3. jQuery code:
$(document).ready(function(){
$('.tableSection tbody tr').click(function()
{
var selected = $(this).hasClass("highlight");
$('.tableSection tbody tr').removeClass("highlight");
$('.buttonSection').attr("disabled", false);
if(!selected)
$(this).addClass("highlight");
});
});
EDIT 1:
With the help of Andrea, I've finally been able to access Struts2 functions with jQuery, the poblem is that I can only access the properties of the last bean on the table (the last one that was accessed when the JSP was rendered, which makes sense). See the updated code below, while I'll try a workaround for this:
JSP:
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr onclick="<s:set var="tid" value="target_id"/>">
[...]
</tr>
</s:iterator>
</s:if>
[...]
<script type="text/javascript">
$(function () {
$('.tableSection tbody tr').click(function(event) {
alert ('<s:property value="%{#tid}" />');
});
});
</script>
EDIT 2:
Now I know which table row index has been clicked, but after hours of trying to assign it to a variable (using Struts tags) and send it to the action, I'm still not getting what I want. I'm not even being able to send this row index to the Action. This is frustrating. Nevertheless, that's how I got to know which row has been selected:
<tr onclick="getRow(this)">
[...]
<script>
function getRow(x)
{
alert("Selected row: "+x.rowIndex);
//return x.rowIndex;
}
</script>
EDIT 3:
This time, I was finally able to send the row ID (a String), to the action. The only remaining issue is that the action gets call twice, the first one on the click event, and the other one because of the href attribute of the a HTML element, which redirects to the desired Struts2 action. Apart of being obviously inneficient, this naturally makes the variable become null on the second call to the action. Do you know how can I somehwow "merge" this 2 calls to the createxperiment2 action into only one? I've tried with the async option in the AJAX call set to false, with no success.
[first, removed the onclick event from the table tr, since I only need to know which row is highlighted when the "Next" button is pressed]. The code currently goes like this:
<script type="text/javascript">
$('#next').click(function(event)
{
var row = $('.highlight').index();
alert (row);
$.ajax({
method: "POST",
url: "createexperiment2.action",
data: { row : row }
});
});
</script>
Q: I have assigned an ID to each table row. How can I know which one is the selected one?
Obtain the object's id with the this keyword:
$('.tableSection tbody tr').click(function(event) {
alert (this.id);
...
Q: how can I use the selected table row ID to access the corresponding bean object (represented in the row itself)?
This is not clear: just submit your id and retrieve the object serverside, no matter if through AJAX or a standard form submit.
Finally, the solution:
First get the ID of the object (I made it with Struts). Then, with the help of an AJAX call, send the ID to the desired action (url: attribute). Upon success of this action, define with the success: callback option where you want to redirect it.
Struts / JSP:
<s:if test="targets.size > 0">
<s:iterator value="targets">
<tr id="<s:property value="target_id"/>" class="highlight">
[...]
</tr>
</s:iterator>
</s:if>
jQuery:
<script type="text/javascript">
$('#next').click(function(event)
{
var tid = $('.highlight').attr("id");
$.ajax({
method: "POST",
url: "createexperiment2.action",
data: { tid : tid },
success:
function()
{
//alert("TID -> "+tid);
window.location = "loadworkloads.action";
}
});
});
</script>
I've been messing around with different forms and tables, now I need something that takes data from table tr and td field, runs a if statement on each fetched item, and outputs text inside the form, depending what was found in td fields.
So right now I have something like this, which doesn't do anything useful at all, for now, just outputs td-01 class values into the form:
var test;
$('tbody tr').each(function(index) {
test = $(this+'.td.td-0');
$('fieldset.csc-mailform').after($('td.td-0'));
});
and my table structure looks something like this:
<table class="contenttable contenttable-3 tabel">
<tr class="tr-even tr-0">
<td class="td-0">01</td>
<td class="td-1">Valik 1</td>
<td class="td-last td-2">150€</td>
</tr>
<tr class="tr-odd tr-1">
<td class="td-0">01</td>
<td class="td-1">Valik 2</td>
<td class="td-last td-2">50€</td>
</tr>
<tr class="tr-even tr-2">
<td class="td-0">01</td>
<td class="td-1">Valik 3</td>
<td class="td-last td-2">170€</td>
</tr>
<tr class="tr-odd tr-3">
<td class="td-0">01</td>
<td class="td-1">Valik 4</td>
<td class="td-last td-2">88€</td>
</tr>
</table>
Right now it only find tr tags and outputs all of them. I need it to split the tr tag up, run if condition on td-0 to determine if it needs to be radio button/text input/checkbox etc, then see what td-1 contains and make that field name, then td-2 is for example a price. all of this should end up in a form.
So as you can see, I am stuck with jQuery, but I think it should be doable.
edit:
I got something like this after messing around a little, but my if statements don't seem to work on jQuery objects, any way to get around this?
var check1;
$('tbody tr').each(function(index) {
//test = $(this+'.td.td-0');
check1 = $('td.td-0');
alert(check1);
if(check1=='01'){
content_type="checkbox";
}else if(check1=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type);
//$('fieldset.csc-mailform').after($('td.td-0'));
});
//edit2
Ugh, I was running if statement against jQuery object, of course it didn't work.
I got it working with this, looks quite nasty, but it seems to work:
$('tr').each(function () { var val = $(this).children('td:first').text();
//$check1 = $('td.td-0');
if(val=='01'){
content_type="checkbox";
}else if(val=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type + '<br/>');
}
);
Now, I need to figure out how to create input fields from these.
You could possibly make it a bit cleaner by using the jQuery selector context, e.g.:
$('tr').each(function () {
var val = $('td:first', this).text();
..
}
Something like this will do:
$('table tr').each(function() {
$tds = $(this).children();
for(var i=0;i<$tds.length;i++){
$td = $tds[i];
if($td.hasClass('td-0'){
//do your thing by getting next TD or something else
break;
}
}
});