JQuery: Assigning value to td span if span is empty - javascript

I have a table with functions connected to a database. If the player score exists, the value is assigned to the td span. If there is no player score, no value is assigned to the td span. I'm trying to populate the span with "0" if a score doesn't exist, or if the td span is empty.
$("table tbody tr").children('td').find("span.playerScore").each(function () {
var test = $(this).text();
if (test === "") {
$(this).parent("td").children('span').text() = "0";
}
})
This isn't working. I definitely feel it's something obvious and I'm just blind so any help is appreciated. Thanks.

This...
$(this).parent("td").children('span').text() = "0";
is not how you set the text of an element.
You need to pass the text as an argument to text:
$(this).parent("td").children('span').text("0");

It might be easier to use the :empty selector. That can save a couple lines of code.
It's important to note that the value of the text has to be enclosed inside parenthesis.
$("table tbody tr").children('td').find("span.playerScore").filter(":empty").each(function () {
$(this).parent("td").children('span').text("0");
})

Related

Append div inside of td and set the value?

I have multiple tables that I need to populate. I use jQuery to loop through table cells. If table cell has data-text attribute I need to append div element. Div element will allow cell to have scroll bar vertical. This way table won't expend if text is too long.
Here is example of my code:
$('#'+tabID+' table tr td').each(function(){
elementID = $(this).prop('id').toUpperCase();
value = $.trim(decodeURIComponent(obj.DATA[elementID]['value']));
if($(this).attr('data-text')) {
$(this).append('<div class="hm_textScroll">'+value+'</div>');
} else {
$(this).text(value).css({'color':'blue','font-weight':'bold'});
}
});
Code above will append div element and set the value but the problem is that if I move to a different table and come back again one more div will append. That creates duplicate. I'm not sure what is the best way to prevent that? Or if there is a better way to work around this. If anyone have suggestions please let me know.
Thanks in advance.
Here you go with a solution
$('#' + tabID + ' table tr').each(function(){
$(this).find('td').each(function(){
elementID = $(this).prop('id').toUpperCase();
value = $.trim(decodeURIComponent(obj.DATA[elementID]['value']));
if(typeof $(this).attr('data-text') != 'undefined') {
if($(this).find('div.hm_textScroll').length > 0){
$(this).find('div.hm_textScroll').text(value);
} else {
$(this).append(`<div class="hm_textScroll">${value}</div>`);
}
} else {
$(this).text(value).css({'color':'blue','font-weight':'bold'});
}
});
});
First loop through each tr then loop through each td.
For check the data-attribute, use typeof $(this).attr('data-text') != 'undefined
In the if statement (true condition) I've used backtick ES6 for appending div container.
Hope this will help you.
If I understand you correctly, you would have to additionally check whether a <div class="hm_textScroll"></div> already exists in the <td>.
One possible solution using vanilla javascript would be this:
const tableElement = document.querySelectorAll('#'+tabID+'table tr td');
tableElement.forEach(td => {
if (td.hasAttribute("data-text")) {
if (!td.querySelector(".hm_textScroll")) {
td.innerHTML='<divclass="hm_textScroll">'+value+'</div>'
}
}
});

Apply CSS on matching text

I am trying to apply a class where text matches with sibling elements.
My certain condition is:
I have a table with multiple rows based on data that I get through database.
One of the td elements has my defined class.
Now I wanted to apply a class only on those td elements where the text of this element matches with another one.
So It would be like, td's whose html/text is equal has that class.
I tried:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
if($(this).html().trim() == $(this).siblings('td').html().trim()) {
$(this).addClass('active');
}else {
$(this).removeClass('active');
}
});
You'd have to iterate each sibling td (or use filter), check for a text match, then add the class:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
var text = $(this).text();
$(this).siblings("td").filter(function() {
return $(this).text() == text;
}).addClass("active");
});
You have to set the value you are searching for and then loop through all table data. If you find a match, add the certain class.
Furthermore you should cache variables in jQuery and avoid using each() function since its performance is really bad compared to for loops.
//cache the element you are searching for
var search = $('.customtd').html().trim();
//cache the whole table so we can use a for loop
var table = $('#table tbody>tr>td');
//use for loop for more performance
for (var i = 0; i < table.length; i++) {
if(table.eq(i).html().trim() == search) {
table.eq(i).addClass('active');
}else {
table.eq(i).removeClass('active');
}
}
Here is a working example:
http://jsfiddle.net/jnh2heuh/2/

Getting the content of the first cell from a dynamically created element inside another cell

I am unable to retrieve the content of the first cell. I'm trying it like this:
console.log($(this).closest("tr").find('td:first').innerHTML);
//or...
console.log($('td:first', $(this).parents('tr')).text());
Code:
$('.editable').click(function () {
var text = $(this).text();
if (typeof $(this).find("textarea")[0]=="undefined")//checking if we have a textarea already
{
$(this).text('');
$('<textarea />').appendTo($(this)).val(text).select().blur(function () {
var newText = $(this).val();
$(this).parent().text(newText).find('textarea').remove();
console.log($(this).closest("tr").find('td:first').innerHTML);
});
}
});
JSfiddle: http://jsfiddle.net/KjknL/
I think the problem has to do with the textarea being added dynamically. But I cannot move from it. If I use .prev() or .next(), it returns empty. Any ideas?
try this: http://jsfiddle.net/KjknL/2/
the textarea doesn't exist anymore because you removed it just before trying to reach the first td from it.
console.log($(this).closest("tr").find('td:first').html());
$(this).parent().text(newText).find('textarea').remove();

jQuery to select elements based on the text inside them

How to select a tag having a specific text inside it and nothing else? For example if I have the following:
<table>
<tr>
<td>Assets</td><td>Asset</td>
</tr>
<tr>
<td>Play</td><td>Players</td><td>Plays</td>
</tr>
</table>
Is there any way that I may select the <td>Asset</td> and nothing else. I tried it with contains i.e. $("table tr td:contains(Play)") but it returns all the tds in the second tr (as it should). Whereas I just want <td>Play</td>.
Is there any way to achieve this, like there's a way to select elements based on their attributes. Is there any way to select elements based on the text inside them?
How about that:
var lookup = 'Asset';
$('td:contains('+ lookup +')').filter(function() {
return $(this).text() === lookup;
});
Demo
Try before buy
Try something like this :
$("table tr td").filter(function() {
return $(this).text() === "Play";
})
If it was an input field you can specify something similar, but a little more exact with $('input[name~="Plays"]) so that it would filter out every other word, leaving the value isolated.
Other than that, the only way I know of doing this with a table is with what you had, but also throwing a conditional statement to check the text inside them.
Here is my version of accomplishing this:
http://jsfiddle.net/combizs/LD75y/3/
var play = $('table tr td:contains(Play)');
for (var i = 0, l = play.length; i < l; i++) {
if ($(play[i]).text() === "Play") {
// your script to modify below
$(play[i]).css({"color" : "red"});
}
}

How can we find the childnode element type in javascript?

I have a table cell and I would like to know if it has a text box inside or simply the span tag in it dynamically using javascrip?
If you want to check whether there's an <input> anywhere inside an element, you could use getElementsByTagName():
if (myTableCell.getElementsByTagName('input').length>=1) {
...do something with the input...
}
You can check the tagName attribute
function isInput(el){
return /input/i.test(el.tagName);
}
or more generic:
function isElType(el,tagname){
return RegExp(tagname,'i').test(el.tagName);
}
//usage
var isInput = isElType(myElement,'input');
Maybe something similar to this:
cell = document.getElementById('tableCell_ID');
spans = cell.getElementsByTagName( "span" );

Categories

Resources