jQuery show a class and hide all others - javascript

this is what I would like to do:
I have this list HTML
<table>
<tr>
<td class = "point">Point1</td>
</tr>
<tr>
<td class = "point">Point2</td>
</tr>
<tr>
<td class = "meanCurvature">mean Curvature 1</td>
</tr>
<tr>
<td class = "meanValue">mean Value 1</td>
</tr>
</table>
and a selector with several options.
Then I have a
JS
if($("#selector").val() == "strain"){
$(".point").show();
$(".meanCurvature").hide();
$(".meanValue").hide();
}
if($("#selector").val() == "curvature"){
$(".meanCurvature").show();
$(".point").hide();
$(".meanValue").hide();
}
if($("#selector").val() == "average"){
$(".meanValue").show();
$(".meanCurvature").hide();
$(".point").hide();
}
I would like to know: now I only have three class and it is handable, but is there a way to say "Show this class and Hide all other"?

I suggest this if you have limited number of rows in your table.
if($("#selector").val() == "strain"){
$(".point").show();
$('td').not('.point').hide();
}
if($("#selector").val() == "curvature"){
$(".meanCurvature").show();
$('td').not('.meanCurvature').hide();
}
if($("#selector").val() == "average"){
$(".meanValue").show();
$('td').not('.meanValue').hide();
}

you may want something like this
if($("#selector").val() == "strain"){
$(".point").show();
$(".point").parent().siblings('tr').children('td').hide();
}

If it were me, I would say
$("td").hide();
$(".desiredClass").show();
This will first hide all your table elements, then reveal the one you're interested in. However, I would also assign a class to your table, so you can avoid interfering with other tables on the page:
<table class="myTable">
...
and the javascript would then be
$(".myTable td").hide()
$(".desiredClass").show()
You could further improve this using advanced selectors
$(".desiredClass").show()
$(".myTable td:not(.desiredClass)").hide()
The above could would avoid any possible 'stuttering' by hiding and then revealing the desired element.

You can do it by showing all tds and then hide the ones that have other classes using not() function. Alternatively you can hid all tds and then show your selected class.
Before doing that, you need to convert your selector value to the desired class using a simple switch.
function apply() {
var selectedVal = $("#selector").val();
switch (selectedVal) {
case "strain":
selectedVal = "point";
break;
case "curvature":
selectedVal = "meanCurvature";
break;
case "average":
selectedVal = "meanValue";
break;
}
$("td").show().not("." + selectedVal).hide();
}
apply();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector" onchange="apply()">
<option>strain</option>
<option>curvature</option>
<option>average</option>
</select>
<table>
<tr>
<td class="point">Point1</td>
</tr>
<tr>
<td class="point">Point2</td>
</tr>
<tr>
<td class="meanCurvature">mean Curvature 1</td>
</tr>
<tr>
<td class="meanValue">mean Value 1</td>
</tr>
</table>
You can make it easier and get rid of the switch if you can change your selector values to match the classes:
function apply() {
$("td").show().not("." + $("#selector").val()).hide();
}
apply();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector" onchange="apply()">
<option value="point">strain</option>
<option value="meanCurvature">curvature</option>
<option value="meanValue">average</option>
</select>
<table>
<tr>
<td class="point">Point1</td>
</tr>
<tr>
<td class="point">Point2</td>
</tr>
<tr>
<td class="meanCurvature">mean Curvature 1</td>
</tr>
<tr>
<td class="meanValue">mean Value 1</td>
</tr>
</table>

you can use the :not selector such as:
$("td:not(.classToActuallyShow)").hide();
Will select all the table data(td) elements and hide them, unless they have a specific class.

My approach would be combine all those classes into one selector. Hide them all then filter the one you want to show based on a stored object that matches the value to the class
var classMatches ={
'strain':'point',
'curvature':'meanCurvature',
'average': 'meanValue'
};
var matchingClass = classMatches[$("#selector").val()];
$('.point, .meanCurvature, .meanValue')
.hide()
.filter('.'+ matchingClass ).show()

You can use not() as selector or as a method to selects all elements except the specified element.
Another way would be use multiple elements selector, like $(".point, .meanValue").hide();But it isnt reccomended if you have a lot of classes in this case.
Check this working example:
$("#selector").change(function(){
if($(this).val() == "strain"){
$(".point").show();
$("td:not(.point)").hide();
}
if($(this).val() == "curvature"){
$(".meanCurvature").show();
$(".point, .meanValue").hide();
}
if($(this).val() == "average"){
$(".meanValue").show();
$("td:not(.meanValue)").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option disabled selected>Select option</option>
<option>strain</option>
<option>curvature</option>
<option>average</option>
</select>
<table>
<tr>
<td class = "point">Point1</td>
</tr>
<tr>
<td class = "point">Point2</td>
</tr>
<tr>
<td class = "meanCurvature">mean Curvature 1</td>
</tr>
<tr>
<td class = "meanValue">mean Value 1</td>
</tr>
</table>

Related

How to get multiple selected cell array values with checkbox in jquery, then send with ajax post

How should I get an array value from a table cell when clicking checkbox with jQuery? If I've selected cell 1, I want to get array like ["BlackBerry Bold", "2/5", "UK"], but if I've selected all of them, I want to get all the data in the form of an array of arrays.
<table border="1">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
Please help.
Onclick get 3 children of the parent and add content to data. Used jquery nextAll for siblings and splice the 3 required.
Attached event to the table, onclick will check if element is INPUT.
If it's input, will get parent of that input which will be <td>.
For this parent element, will get three siblings using jquery.
Will add in selected if not present else delete, using indexOf.
CodePen for you to playaround: [ https://codepen.io/vivekamin/pen/oQMeXV ]
let selectedData = []
let para = document.getElementById("selectedData");
let tableElem = document.getElementById("table");
tableElem.addEventListener("click", function(e) {
if(e.target.tagName === 'INPUT' ){
let parent = e.target.parentNode;
let data = [];
$(parent).nextAll().map(function(index, node){
data.push(node.textContent);
})
let index = selectedData.indexOf(JSON.stringify(data))
if(index == -1){
selectedData.push(JSON.stringify(data));
}
else{
selectedData.splice(index,1);
}
para.textContent = "";
para.innerHTML = selectedData ;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="table">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
</table>
<h3> Selected Data: </h3>
<p id="selectedData"></p>
Updated to meet your needs.
create a function to build the array values based on looking for any checked inputs then going to their parents and grabbing the sibling text values
attach your change event to the checkbox click even.
I provided a fiddle below that will output the array in the console.
function buildTheArray(){
var thearray = [];
$("input:checked").parent().siblings().each(function(){
thearray.push($(this).text());
});
return thearray;
}
$("input[type='checkbox']").change(function(){
console.log(buildTheArray());
});
Fiddle:
http://jsfiddle.net/gcu4L5p6/

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows.
Consider following table:
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1'> dummy1 </td>
</tr>
<tr>
<td name='Key1'> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2'> dummy3 </td>
</tr>
<tr>
<td name='Key2'> dummy4 </td>
</tr>
</table>
jsfiddle
Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?
I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.
Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/
$('input').keyup(function(){
$('tr').hide();
$("td").filter(function() {
return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
});
});
Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/
<input type="text" id="myInput" />
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1' class="data"> dummy1 </td>
</tr>
<tr>
<td name='Key1' class="data"> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2' class="data"> dummy3 </td>
</tr>
<tr>
<td name='Key2' class="data"> dummy4 </td>
</tr>
</table>
.data{
display:none;
}
var theData = $('td.data');
var input = $('#myInput').on('keyup', function(){
theData.hide();
var value = input.val();
var matches = theData.filter('[name="'+value+'"]');
matches.show();
});
Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).
Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:
JS Fiddle Demo
It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

get data attribute and append optimize

I have been fiddling around and with some code I found here I managed to get some working code although I wonder if it can be optimized further.
I have tried to comment the code so my thought process is shown. If anyone knows a better way to achieve to [get the data-tid attribute and append the value to a span in that tablerow to a td] I would love to hear it.
<table>
<tr data-tid="3"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="2"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="5"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="6"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
</table>
$j = jQuery.noConflict();
$j(document).ready(function() {
topiclistview = $j('[data-tid]').length;
// check if data-tid exists
if (topiclistview > 0) {
//set vars
var tids = $j('[data-tid]');
var tids_array = [];
//get the data attribute values and put them in an array
$j(tids).each(function(index, item) {
tids_array.push($j(item).data('tid'));
});
//run over all tr with the class .col_f_content and append the attribute value
$j('.col_f_content').each(function(index, item){
$j('<span>'+tids_array[index]+'</span>').appendTo($j(item));
//console.log('tr item'+tids_array[index]);
});
}
});
Performance-wise? This is probably a good shot:
// iterate over all elements having the data-tid attribute
$("[data-tid]").each(function() {
// Create our span. No need for a jQuery wrapper.
var span = document.createElement("span");
// Set the span text. No need to involve jQuery's data() function
span.appendChild(document.createTextNode(this.getAttribute("data-tid")));
// Add the span to your second cell (col_f_content). This should be way faster
// than creating a new jQuery object via class selector.
this.cells[1].appendChild(span);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>
Alternatively, depending upon your needs, you could achieve something similar with CSS only:
tr[data-tid]:after {
display: table-cell;
vertical-align: middle;
content: attr(data-tid);
}
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>
I'd try something like this:
$('[data-tid]').each(function(){
var value = $(this).data('tid');
$('<span>' + value + '</span>')
.appendTo($(this).find('.col_f_content'));
});
(PS: Untested)
You don't need to use intermediate arrays, and you can store the set of elements the first time you select them (when you test if there are any elements with [data-tid]).
It should be more performant to select based on a class, so if it's possible to add a class a class to the data-tid element html, we could use that for our selector.
$(document).ready(function() {
'use strict';
// We want to work with these elems
var topiclist = $('[data-tid]');
if (topiclist.length > 0) {
// Just get the data, make a new elem and append it
// All in 1 pass
topiclist.each(function(_, el) {
var $el = $(el);
$el.append('<td>' + $el.data('tid') + '</td>');
});
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<table>
<tr data-tid="3"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="2"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="5"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="6"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
</table>
Also note, I'm appending a <td> with your contents to the <tr>, which is the element you selected. <span> is not a legal child of <tr>. If you want to do something with a <span>, you'll need to wrap it in a <td> if it's in a table.

How to hide tr items when td is 0 in jquery?

I want to hide all of the <tr> where td's text is 0. How can I do that? I have to mention that in reality i have more than 600 rows. But the example below is a demo. THX
<table id ="list2">
<tbody>
<tr>
<td>2</td>
<td>213</td>
<td id ="hideRow">0</td>
<tr>
<tr>
<td>vb</td>
<td>asf</td>
<td id ="hideRow">0</td>
<tr>
<tr>
<td>cxvb</td>
<td>xcvb</td>
<td id ="hideRow">2</td>
<tr>
<tr>
<td>cas</td>
<td>asdf</td>
<td id ="hideRow">45</td>
<tr>
</tbody>
</table>
This is my try :| . The event is loaded by onclick event
$('#list2').find("tr td #hideRow").each(function(){
var txt2 = $(this).text();
if (txt2 =="0"){
$('#list2').find("tr").each(function(){
$(this).hide();
});
}
})
First of all do not use id for duplicate names. Try doing it like following.
<table id ="list2">
<tbody>
<tr>
<td>2</td>
<td>213</td>
<td class="hideRow">0</td>
<tr>
<tr>
<td>vb</td>
<td>asf</td>
<td class="hideRow">0</td>
<tr>
<tr>
<td>cxvb</td>
<td>xcvb</td>
<td class="hideRow">2</td>
<tr>
<tr>
<td>cas</td>
<td>asdf</td>
<td class="hideRow">45</td>
<tr>
</tbody>
</table>
$('#list2').find(".hideRow").each(function(){
var txt2 = $(this).text();
if (txt2 =="0"){
$(this).parent().hide();
}
})
IDs on elements need to be unique, you can't have multiple <td id="hideRow"> elements and expect things to play nicely all of the time. I'd suggest changing it to a class. Then, select all elements:
var elems = $('span.hideRow');
Filter to those whose text is 0:
elems = elems.filter(function() {
return $(this).text() === "0";
});
Get their parent <tr> element:
elems = elems.closest('tr');
Then, finally, hide them:
elems.hide();
That can, obviously, all be done in one line:
$('span.hideRow').filter(function() {return $(this).text() === "0";}).closest('tr').hide();

How to include rowspan and colspan dynamically inside <td> tag based on some conditions

I know I can include <td colspan=10> statically when I want to merge the columns, but if I need to check some conditions and based on that only I need to merge then how this could be done?
My idea was like this:
var span="";
if(some condition)
span="colspan=10";
and then setting this variable inside <td> as:
<td +span+>
but it doesn't work like that… Any suggestion how to do this?
<table id="table" border=2>
<tr id="row1">
<td id="tableCellID">foo</td><td></td>
</tr>
<tr>
<td>foo</td><td>foo</td>
</tr>
</table>
<button onclick="button();" text="Change"/>
<script language="javascript">
var i = 0;
function button(){
var td = document.getElementById("tableCellID");
if(i==0){
td.setAttribute("colspan", 2);
i=1;
}else{
td.setAttribute("colspan", 1);
i=0;
}
}
</script>
This is how you can dynamically set the attribute colspan. You will see that changing the colspan of one cell will effect the layout of the entire table. You will need to deal with each cell in the row.
var span='';
var table='';
if(some condition)
span="colspan=10";
var table="<tr><td"+span+"></td></tr>":
One way to do is, if you able to set an id in your td
<td id="foo">
in your javascript, you can add attributes like this,
document.getElementById("foo").colSpan="10";
document.querySelector("tr.total td").style.backgroundColor = "#ccc";
document.querySelector("tr.grand td:nth-child(1)").colSpan="2";
document.querySelector("tr.grand td:nth-child(2)").remove();
table, table td {border:1px solid #ccc; padding:5px 10px; border-spacing:0px;}
.grand{font-weight:bold;}
<table>
<tr>
<td>Column</td>
<td>Value</td>
</tr>
<tr class="total">
<td>Sub Cost</td>
<td>$500</td>
</tr>
<tr class="grand">
<td>Amount $1000</td>
<td>Remove Me</td>
</tr>
</table>

Categories

Resources