jquery table selector with condition - javascript

i had a table that submitted from my jquery append script, are its possible to find the match value with jquery selectors,
i want to check if the condition >= var $minimumEducation, it will pass to next page when submit, i set the value 0 for High School, 1 for Diploma and so on as it use selectbox, the var $minimumEducation variable come from my php admin, anyone knows how to pass this condition ? thanks
<thead>
<tr>
<th>Name</th>
<th>Relation</th>
<th>DOB</td>
<th>Education</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Uncle</td>
<td>02/19/1955</td>
<td>Bachelor</td>
<td>Carpenter</td>
</tr>
<tr>
<td>Amy</td>
<td>Aunty</td>
<td>02/19/1950</td>
<td>Master</td>
<td>Housewife</td></tr>
<tr>
<td>Eddie</td>
<td>Cousin</td>
<td>02/19/1990</td>
<td>Diploma</td>
<td>Editor</td>
</tr>
</tbody>
</table>

You can select each matched element using the :has selector. To match against minimum education you must build the selector string based on the array mapping the education strings to the $minimumEducation value
$( "tr:has(td[value="bachelor"], td[value="master"])" )
This can be generated similar to the following
var query = "";
for (var i = minimumEducation; i < eduarray.length; i++) {
query += ', td[value="'+eduarray[i]+'"]';
}
query = query.substring(1);
Then just put the query string inside the selector
$( "tr:has("+query+")" )

Related

I can't collect in Javascript

I'm new to javascript, I want to place a code in my html page like the following, but I get a NaN error or no error. He just doesn't make the sums. My html page is in Turkish but I hope you will understand. Thanks in advance for your suggestions and help
in two different tables
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
it needs to show a total in another table
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
Here is the javascript:
{
var hb1= document.getElementById("Hizmet_Bedeli1").textContent; // If I use .value also, it doesn't work if I use .textContent as well.
var hb2= document.getElementById("Hizmet_Bedeli2").textContent; // .value de kullansam .textContent de kullansam düzelmiyor
var hizmet_toplam= parseInt(hb1) + parseInt(hb2); //parseInt de kullansam Number de kullansam Nan hatasıalıyorum... // If I use parseInt with Number, I get Nan error ...
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
I want to add the textContent of #Hizmet_Bedeli1 and #Hizmet_Bedeli2 together.
You are most probably not wrapping your tr and th tags in a table tag, which will cause your browser to not render the elements.
{
var hb1 = document.getElementById("Hizmet_Bedeli1").textContent;
var hb2 = document.getElementById("Hizmet_Bedeli2").textContent;
var hizmet_toplam = parseInt(hb1) + parseInt(hb2);
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
<table>
<tr>
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
<tr/>
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
</table>

How can I remove the div tags from a html table using jquery or javascript?

I'm looking to remove the divs from a html table but retain the content?
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
I have tried:
alert($('#datatable').html().replace('<div>', ''));
But what is alerted still contains the
<div>
tags
I can't remove them from the source because they are used for other purposes.
To keep the DOM unmodified (IE: Leave the <div> tags in the source) and only modify the HTML variable you can do:
var html = $('#datatable').html();
var tags = ["<div>", "</div>"];
for (var i = 0; i < tags.length; i++) {
while (html.indexOf(tags[i]) > -1) {
html = html.replace(tags[i], "");
}
}
alert(html);
This is available as a demo at this fiddle.
The problem with your initial solution, is that JavaScript replace only removes the first occurrence of the specified string. Hence the while loop.
Use $('#datatable div').contents().unwrap() to remove the divs from the table and alert($('#datatable').html()) to show the remaining elements of the table.
var backup = $('#datatable').html();//Keep the html
$('#datatable div').contents().unwrap();//Remove divs
alert($('#datatable').html());//Show the table (without divs)
$('#datatable').html(backup);//Bring the old, full html back
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
Try this
$('#datatable').find('div').remove();
If you want to keep content try this
$('#datatable').find('div').replaceWith(function(){
return $(this).text()
});
$('#datatable').find('div').replaceWith(function(){
return $(this).text()
});
alert($('#datatable').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
actually there are 3 common ways
1. Using the .html('') method
$("#my_element").html(''); // the quotes are important as just .html() returns the html DOM container within the target element
2. Using the .remove() method
$("#my_element #my_element_child").remove(); // removes the targeted child element
3. Using the .empty() method
$("#my_element").remove(); // similar to the .html('') method it removes all children divs
Edit It seams i have made a mistake in understanding the OP's original intention as pointed out by #JosephGarrone and hence i made the following edit.
var dom = $("#my_element").html() // get the elements DOM structure
var regex = /(<div>|<\/div>)/g; // a regex to pickup the <divs in the DOM
var div_less_dom = dom.replace(regex, '') // do something with the "<div>" free DOM
One approach, in plain JavaScript is:
// a descriptive, but ridiculously named, function,
// htmlString: String, the string of HTML from which
// you wish to remove certain element-types,
// toRemove: String, the element-type you wish to remove,
// this is passed to querySelectorAll(), so a
// CSS selector is fine, although to guard against
// '<div>' I have removed '<' and '>' characters:
function removeElementFromHTMLString(htmlString, toRemove) {
// here we create a <div> element:
let div = document.createElement('div'),
// and declare an 'empty' variable for
// later use:
parent;
// here we convert the supplied selector to lower-caase,
// and remove the '<' and '>' characters to prevent
// errors from the user supplying '<div>', converting it
// to 'div'; this does mean that the child combinator '>'
// cannot be used in the selector (as currently written):
toRemove = toRemove.toLowerCase().replace(/<|>/g,'');
// assigning the htmlString as the innerHTML of the
// created-<div>:
div.innerHTML = htmlString;
// passing the supplied selector to querySelectorAll(),
// converting the Array-like NodeList to an Array, and
// iterating over that Array with Array.prototype.forEach():
Array.from(div.querySelectorAll(toRemove)).forEach(function(elem){
// 'elem' refers to the current element in the Array of
// elements over which we're iterating:
// assigning the elem.parentNode to a variable for reuse:
parent = elem.parentNode;
// while the found element has a first child:
while (elem.firstChild) {
// we insert that first child ahead of the
// current element:
parent.insertBefore(elem.firstChild, elem);
}
// and then, once the element has no child
// elements, we remove the element from its
// parent:
parent.removeChild(elem);
});
// and then, assuming you want a HTML String without
// those elements matching the selector, we return
// the innerHTML to the calling context:
return div.innerHTML;
}
console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));
function removeElementFromHTMLString(htmlString, toRemove) {
let div = document.createElement('div'),
parent;
toRemove = toRemove.toLowerCase().replace(/<|>/g, '');
div.innerHTML = htmlString;
Array.from(div.querySelectorAll(toRemove)).forEach(function(elem) {
parent = elem.parentNode;
while (elem.firstChild) {
parent.insertBefore(elem.firstChild, elem);
}
parent.removeChild(elem);
});
return div.innerHTML;
}
console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));
td {
color: orange;
}
td > div {
color: limegreen;
}
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td>
<div>3</div>
</td>
<td>
<div>4</div>
</td>
</tr>
</tbody>
</table>

How to read a list of html tables in JavaScript

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!

How to get a table td index based on the tr class name?

I have a table with the below details how to get the td index based on the tr class name
<Table id="#Hs_tbl">
<thead>
<th>country</th>
<th>state</th>
<th>city</th>
</thead>
<tr>
<td>india</td>
<td class="htInvalid">Bnagalore</td>
<td class="htInvalid">mysore</td>
</tr>
</table>
Now need the td tag index of based on the class="htInvalid"; here is what I have tried, I am able to get only one TD name, how to get both td names. Here is my code:
var col = $("#Hs_tbl tr").find("td." + "htInvalid").index();
How to get both the column name?
Either, You need to remove # from ID attribute of table.
<table id="Hs_tbl">
OR, You need to escape # meta character in selector like
$("#\\#Hs_tbl tr").find("td." + "htInvalid").index()
Docs
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.
To get all the all text, map() can be used
var alltdtext = $("#\\#Hs_tbl tr").find("td.htInvalid").map(function(){
return $(this).text();
}).get();
You can also directly use the class .htInvalid and loop through each of them to get the text & it's index
var alltdtext = $(".htInvalid").each(function(){
var a =$(this).text(); // Bangalore,mysore
var index =$(this).index(); //1,2
console.log(a ,index)
})
JSFIDDLE
First of You need to escape the meta character in id attribute :
$("#\\#Hs_tbl tr");
or use attribute equals selector:
$("[id='#Hs_tbl'] tr")
And for getting the text, You can use .map() function to get jquery object of text properties of elements along with .get() to convert them to array:
var alltdtext = $("#\\#Hs_tbl tr").find("td.htInvalid").map(function(){
return $(this).text();
}).get();
Working Snippet:
var alltdtext = $("#\\#Hs_tbl tr").find("td.htInvalid").map(function(){
return $(this).text();
}).get();
console.log(alltdtext);
<Table id="#Hs_tbl">
<thead>
<th>country</th>
<th>state</th>
<th>city</th>
</thead>
<tr>
<td>india</td>
<td class="htInvalid">Bnagalore</td>
<td class="htInvalid">mysore</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Dynamically remove tableDatas from table

Update Code working Here
I have a table populated with teacher's disciplines that has: day of the week and it's time period, of course it also have the disciplines.
Now I need to remove those items.
Table:
<table id="prof-table">
<tbody><tr>
<th>HORÁRIO</th>
<th data-dia="mon">Monday</th>
<th data-dia="tue">Tuesday</th>
<th data-dia="wed">Wednesday</th>
<th data-dia="thu">Thursday</th>
<th data-dia="fri">Friday</th>
</tr>
<tr>
<td>08:30 ~ 10:30</td>
<td><ol><li data-id="6" data-prof="4">Calculo A</li></ol></td>
</tr>
<tr>
<td>10:30 ~ 12:30</td>
td></td><td><ol><li data-id="2" data-prof="4">Lab II</li></ol></td>
</tr>
<tr>
<td>14:30 ~ 16:30</td>
</tr>
<tr>
<td>16:30 ~ 18:30</td>
</tr>
<tr>
<td>18:30 ~ 20:30</td>
<td></td><td></td><td></td><td></td><td><ol><li data-id="5" data-prof="4">Estatistica</li></ol></td>
</tr>
<tr>
<td>20:30 ~ 21:30</td>
</tr>
<tr>
<td>21:30 ~ 23:30</td>
</tr>
</tbody></table>
What I did so far is to get the <td> from the rows but I don't know how to work with it, tried to use .each() from JQuery but I just cant do it.
Javascript:
var myRow = document.getElementById("prof-table").rows[range.index + 1];
var test = $(myRow.getElementsByTagName('td')).not(':first-child');//Skip the first td because its the time period of the discipline.
console.log(teste);
Now if you check the console.log() this is what is shown:
As you can see, there are three lines. Each line/obj has the exactly number of <td>s from the row.
What I need to do is loop through each of these lines. Also I need to reset the index for each loop.
EX: While interacting with the first line of the image, my Index goes from 0 ~ 1. Then when start the second line I need to start my index from 0 again untill 4 (because it has 5 elements td)
Tried something like:
$.each(teste, function(index, obj){
if($(obj).text() == "")
myRow.deleteCells(index);
});
But as the index doesnt "reset" for each of those lines in the picture, I get error about overflowing the row index limite. Because while the first row has only one <td> member, the last has 5, as the index is always growing ++ I get that error. And I have no idea how to work around it.
Because I don't understand you situation well, I create two function
To delete data based on "data-prof" attribute of "li" inside the "td"
To delete all data of the table.
In my oppinion, if you assign "data-prof" value to the "td" instead of "li", it'll boost performance.
Hope it's help.
Function to delete data based on "data-prof" attribute:
function resetTableData(dataProf) {
// Get cell list by data-prof
var $cellList = $("#prof-table").find("li[data-prof = " + dataProf + "]").closest("td");
$cellList.each(function(){
$(this).html(""); //Remove inner HTML of cells.
});
}
Function to delete data of all cells:
function resetTableData() {
// Get row list
var $rowList = $("#prof-table").find("tr").not(":first"); // First row is the header, don't need to select.
// Loop row list and get cell list of each
$rowList.each(function(){
// Cell list
var $cellList = $(this).find("td").not(":first"); // First column is time period, don't delete it.
// Loop cell list and delete content
$cellList.each( function() {
$(this).html(""); //Remove inner HTML of cells.
});
});
}

Categories

Resources