how to add variable to 'classname' in jquery using match function? - javascript

I want to check the classname with pattern eg. sort-order12, sort-order13 using the match function in jquery.
The below usage is not working. Anyone can help ?
var sort_order = $('.js-data-selector.active:first').data('sort-order');
sort_order_next -> is the variable containing integer value.
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(/"sort-order"+(sort_order_next)/)
}).closest("tr");
child.show();
I am trying to display the nodes with classname with pattern "sort-order-1", "sort-order-2" etc. according to the node value (sort-order-next) obtained.

Try this
var sort_order_next = 12;
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(new RegExp('sort-order-' + sort_order_next));
}).closest("tr");
console.log(child);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="sort-order-12"></td>
</tr>
<tr>
<td class="sort-order-13"></td>
</tr>
<tr>
<td class="some-cls"></td>
</tr>
</table>

Related

td background colouring applied to complete column rather to a single cell

I've below html.
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
Below is the jquery I've written.
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')').text());
}
}); var idx2 = [];
for(var x=0;x<list2.length;x++){
if(list[x]===list2[x]){
//console.log(list[x]);
}else{
console.log('mismatched : '+list[x]);
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
idx2.push(x);
}
}
});
I'm trying to compare values in list with values in lqwasb02 column and if it finds the difference, it should highlight the background of td cell in red colour.
Current issue with jquery code, it is highlighting the complete column.
Can someone please help me where I'm getting wrong? If possible, please pass on the recommended solutions.
Many Thanks in advance.
The problem is that in your .find you are returning multiple elements that it's selector matches. So as opposed to storing the text value for your td elements in the second array, just store the actual td element, compare it's text, and then you can assign the background color directly to the element as opposed to finding it again via it's index:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')')); // <-- Store the object here, not it's text value.
}
});
var idx2 = [];
for(var x=0; x < list2.length; x++){
if(list[x]===list2[x].text()) { // <-- compare list[x] to the text value of list2[x]
//console.log(list[x]);
} else {
list2[x].css("background-color", "red"); // <-- no find or selector needed, just apply it to the object you stored earlier.
};
idx2.push(x);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
this piece of code assign a background colour to each cell of index 'x' for each rows (each cells of index x of each table rows represent a column).
You have to select only the rows which contains the cells you want to colour.
Here is how i would have approached solving this issue:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
var colIndex = findColIndex('lqwasb02');
// Loop over table rows
$('tr').each(function(){
// Look up cell with specific index
var $cell = $(this).find('td').eq(colIndex);
// Check if the text of the cell is not present in the list and do smth
if ($.inArray($cell.text(), list) === -1) {
$cell.css('background', 'red')
}
});
});
// helper function to find the index of column by text in the header
function findColIndex (headerText) {
var $col = $('.myTable th:contains(' + headerText + ')');
return $('.myTable th').index($col);
}
https://jsbin.com/fafegi/1/edit?js,output

How can I fix jquery when i change table elements to div style in body section?

<body>
<input type="text" id="search"/>
<table id="boxdata">
<tr>
<td class="namebox1">jQuery</td>
</tr>
<tr>
<td class="namebox2">javascript</td>
</tr>
<tr>
<td class="namebox3">php</td>
</tr>
<tr>
<td class="namebox4">sql</td>
</tr>
<tr>
<td class="namebox5">XML</td>
</tr>
<tr>
<td class="namebox6">ASP</td>
</tr>
</table>
</body>
<script>
$(document).ready(function(){
$('#search').keyup(function(){
searchBox($(this).val());
});
});
function searchBox(inputVal) {
$('#boxdata').find('tr').each(function(index, row){
var names = $(row).find('td');
var found = false;
if(names.length > 0) {
names.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()) & inputVal != ''){
found = true;
return false;
}
});
if(found == true)
$(row).addClass("red");
else
$(row).removeClass("red");
}
});
}
</script>
there's a textfield for searching words and there are 6 words in the each 6 boxes below textfield.(I omitted css codes. but, it wouldnt matter to solve the problem.). if i type a letter 's' then the words that including letter 's' like 'javascript', 'sql', 'ASP' these font-color will be changed black to red. And i made it by using table elements in html but i'd like to change all elements into div style to put some data fluidly later. i have difficulty to fix especially jquery. how can i fix it?
You can simplify this a little bit.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal, 'i');
$('#boxdata').find('tr').removeClass('red').filter(function() {
return $(this).find('td').filter(function() {
return regExp.test( $(this).text() );
}).length && $.trim(inputVal).length;
}).addClass('red');
}
So remove the red class from all <tr>'s first, then filter them, test the text of each <td>, if it matches, return the <tr> and then add the class red again.
Here's a fiddle
As for changing from a table to div, the jQuery would depend on how you structure your markup, but the principle would remain the same.
Here's another fiddle
You can make javascript code HTML agnostic by using css classes instead of element names. Demo.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal = $.trim(inputVal), 'i'),
highlight = 'red';
$('#wrapper').find('.word') //instead of tr/td/div
.removeClass(highlight)
.each(function(){
var $this = $(this);
inputVal && regExp.test($this.text()) &&
$this.addClass(highlight);
});
}

How to match everything before an underscore in class names and replace with a word

Fiddle Example
The table has class names like:
dsdds_image,dfdd_image,sdadsa_title,dsdf_title,3434_description,48fd_description.
They are just random strings before the underscore. How would you replace all these random strings with the word "placeholder" in jQuery so that they become placeholder_title,placeholder_image,placeholder_description?
HTML:
<button id="cleartable">Clear</button>
<table class="toptable">
<tr>
<th class="dsdds_image">1</th>
<th class="r3dde_image">2</th>
<th class="s43434_image">3</th>
</tr>
<tr>
<td class="44665_description">4</td>
<td class="3434d_description">5</td>
<td class="a34df_description">6</td>
</tr>
<tr>
<td class="dfs4rf_title">7</td>
<td class="adf43df_title">8</td>
<td class="dsffds4_title">9</td>
</tr>
</table>
My failed attempt
$("#cleartable").click(function() {
$(".toptable td,.toptable th").each(function() {
var changeclass = $(this).attr("class");
changeclass.replace(/^[^_]+/,"placeholder");
});
});
You can simply do this:
$("#cleartable").click(function() {
$(".toptable td,.toptable th").each(function() {
var changeclass = $(this).attr("class");
$(this).attr('class',changeclass.replace(/^[^_]+/,"placeholder"));//See this?
});
});
.replace gives you a new string and will not change the original. So, you'll need to reassign it somewhere.
Something like this seems a lot easier
$('#cleartable').on('click', function () {
$('td, th', '.toptable').attr('class', function(_, klass) {
return 'placeholder_' + klass.split('_').pop();
});
});
FIDDLE
Change your code to
$("#cleartable").click(function() {
$(".toptable td,.toptable th").each(function() {
$(this).attr("class", changeclass.replace(/^[^_]+/,"placeholder"));
});
});
As you were not assigning the replaced class back to the elements picked

How to get <td> value in textbox

I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />​
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});​
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});

Nested tag name with getElementsByTagName doesn't work

I have the following div that contains the table and its data queried from database
<div id="content">
<table>
<tbody>
<tr>
<th class="header" colspan="2">Food items include:</th>
</tr>
<tr>
<td id="15" class="fruits">Papaya+salt</td>
<td><p>This includes papaya and salt</p></td>
</tr>
<tr>
<td class="meat">Baked chicken</td>
<td><p>This includes a chicken thide and kethup</p></td>
</tr>
<tr>
<td id="1" class="Juices">Strawberry Sting</td>
<td><p>Sugar, color and water</p></td>
</tr>
<table>
</div>
That table is defined in a page.aspx
and here is my code used to sort that table data alphabetically
OldFunc = window.onload;
window.onload = OnLoad;
function OnLoad(){
try{
var pathName = window.location.pathname.toLowerCase();
if( pathName=="/Resources/Glossary.aspx") {
sort_it();
}
OldFunc();
}
catch(e) {
}
}
function TermDefinition(def_term,def_desc)
{
this.def_term=def_term;
this.def_desc=def_desc;
}
function sort_it()
{
var gloss_list=document.getElementsByTagName('td');
var desc_list=document.getElementsByTagName('td p');
var gloss_defs=[];
var list_length=gloss_list.length;
for(var i=0;i<list_length;i++)
{
gloss_defs[i]=new TermDefinition(gloss_list[i].firstChild.nodeValue,desc_list[i].firstChild.nodeValue);
}
gloss_defs.sort(function(a, b){
var termA=a.def_term.toLocaleUpperCase();
var termB=b.def_term.toLocaleUpperCase();
if (termA < termB)
return -1;
if (termA > termB)
return 1;
return 0;
})
for(var i=0;i<gloss_defs.length;i++)
{
gloss_list[i].firstChild.nodeValue=gloss_defs[i].def_term;
desc_list[i].firstChild.nodeValue=gloss_defs[i].def_desc;
}
}
Please lookat the the two getElementsByTagName, I think I am misuse its content since nothing is done on the output.
Invalid:
desc_list=document.getElementsByTagName('td p');
You can't pass a css selector to that function, only a tag name like div\ span input etc'.
You might want to use:
desc_list = $('td p');
Since you tagged the question with jQuery, or document.querySelectorAll for vanilla js:
desc_list = document.querySelectorAll('td p');

Categories

Resources