jquery select an element using comments inside it [duplicate] - javascript

This question already has answers here:
Get text inside HTML comment tag?
(2 answers)
Closed 8 years ago.
I need to select the table cell, that has a comment, which contains the word "Baseline EUI" and in that cell I need to add unit name next to the value ("59") like km or miles etc. How do I select the cell, provided the only thing that uniquely identifies that table cell is the keyword inside the comment i.e. "Baseline EUI" ? Please help me how I can select this table cell using jQuery? (I need to add unit like Km or Miles right after the number 59 in the table cell)
<tr>
<td width="165" class="ms-formlabel" noWrap="nowrap" vAlign="top">
<H3 class=ms-standardheader><A name=SPBookmark_BaselineEUI></A>Baseline EUI</H3>
</td>
<td width="450" class="ms-formbody" id="SPFieldNumber" vAlign="top">
<!-- FieldName="Baseline EUI" FieldInternalName="BaselineEUI" FieldType="SPFieldNumber" -->
59
</td>
</tr>
<tr>
There are many rows/cells like the above...
</tr>

I haven't test this code. But it should work in your case.
please verify and make necessary changes.
$.each($("yourtable tr"),function(i,val){
var check=false;
//check if Baseline EUI is contained inside tr
if($(val).html().indexOf('Baseline EUI'))
{
var x=$(val).find('td')[1];
var p=$(x).html()+' km';//set your suffix
$(x).html(p)
}
});
or use this as a selector of the right tr:
$(".ms-formtable tr").filter(function (i, v) { if ($(this).html().indexOf('Zugehoerigkeit') > 0) { return this; } })

First you select the tr tag then loop throw the contents of each tr tag searching for the content which contains the word you are searching for .
$( "tr" ).each(function() {
});
For adding the unit you want, you would do the same but when you find that cell, you will the index method of jquery to know where the number is and then use jquery substring method to split the value of that cell in two parts adding your unit to the first part and then make the value of that cell = the first part (after adding your unit) + the second part (using jquery substring method).
Please, let me know in the comments if you need detailed code .

Related

Make some columns not editable with Mindmup editable table

I am using Mindmup editable tables.
I would like that the last column to not be editable (because in my case, it is a button to remove the row).
Can I do that with this library ?
There is currently no support for this feature.
But a quick fix is the following (based on this issue):
Change the line 113 of the plugin from this:
element.find('td').prop('tabindex', 1);
To this:
element.find('td[data-editable!="false"]').prop('tabindex', 1);
And in your table, make the appropriate columns not editable like this:
<tr data-id=123">
<td data-colname="first_name"
>Chuck</td>
<td data-colname="last_name"
>Norris</td>
<td data-editable="false"> <!-- data-editable added here -->
<button type="button" class="btn">
<i class="ti-close" aria-hidden="true"></i> Remove
</button>
</td>
</tr>
Note: the weird formatting of the td tags is intentional: this way, the editable plugging doesn't insert white spaces while editing a cell.
Update line 92 in mindmup-editabletable.js to:
$('.someClass').on('click keypress dblclick focus', showEditor)
Update line 114 in mindmup-editabletable.js to:
element.find('.someClass').prop('tabindex', 1);
Now apply class="someClass" to each of the elements that you want to be able to edit in your table.
Also, to remove the white space in the table cells, you can modify line 18 of the mindmup-editabletable.js to be:
editor.val(active.text().trim())
replace the line 16 (in the showEditor function):
active = element.find('td:focus');
with this code
active = element.find('td:focus').filter(function(){
var i= -1;
var elem = this;
do {++i} while((elem=elem.previousSibling)!=null);
return !(activeOptions.disableColumnNumbers.indexOf(i) > -1);
});
and then you will be able to declare your editor using disableColumnNumbers option like this
$("selector...").editableTableWidget({disableColumnNumbers: [0,2,3,4,5,6,7,8,9,10,11,12]});
good luck mate

How do I define all table captions on my website as anchors in JavaScript?

I have a Jekyll-powered GitHub pages website on which, I'd like to hyperlink to where in my posts my tables are and at the moment the only way I know how to do this is by placing a heading immediately before the table. This in turn allows me to hyperlink to the heading that is immediately before the table. For example, https://fusion809.github.io/2015/12/27/comparison-of-free-operating-systems/#programming-languages links to the "Programming Languages" heading in my "A Comparison of Free Operating Systems" post, which is close to, but not immediately before my table entitled "Table 1: A Comparison of Common Programming Languages". Is there a way I can make all table captions (defined with the <caption> tag between <table> and </table> tags) anchors by modifying my website's JavaScript? My table names (or captions) are usually quite long, so if it is possible to use a counter for each, giving them each a number according to their position in my post and then using that for the hyperlink? For example, for the aforementioned post my first table would have the URL https://fusion809.github.io/2015/12/27/comparison-of-free-operating-systems/#table1.
Please try to simplify your answer into simple actions like exactly what I need to add to my website's JavaScript, CSS or HTML as my programming/markup knowledge is in its infancy and hence if you through me in the deep end odds are I'll drown.
You don't need anchors or other additional tags -- any id in the document can be linked to via http://example.com/mypage#someid
Assuming the caption text is unique, you can loop through each one and give it an id based on its text (after removing non-alphanumeric characters). I've prefixed each id with "table-", and lowercased them as well.
In this example, you'd end up with #table-one, #table-two and #table-threefour links available:
$('caption').each(
function() {
var cap = this;
var text = $(cap).text();
// just a-z, 0-9, - and _
var id = text.replace(/[^a-z0-9\-\_]/g, '').toLowerCase();
cap.id = "table-" + id;
}
);
table {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<caption>one</caption>
<tr>
<td>td</td>
</tr>
</table>
<table>
<caption>Two</caption>
<tr>
<td>td</td>
</tr>
</table>
<table>
<caption>three four</caption>
<tr>
<td>td</td>
</tr>
</table>
If the captions are not unique, you can use a counter and just give them ids like #table1, #table2, etc.
var counter = 0;
$('caption').each(
function() {
++counter;
this.id = 'table-' + counter;
}
);

jquery selector from html comment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have little big problem. I try almost everything and I am not able to select an element from table if I know some commented text. I think that this is not possible. For example
<table id='table1'>
<tr>
<td>
Some text
</td>
<td>
<!-- someid="id301" -->
</td>
</tr>
<tr>
<td>
Some next text
</td>
<td>
<!-- someid="id303" -->
</td>
</tr>
<table>
OK. So I only know for example this value someid="301" or someid="302". And I need to get parent element for example to change color of this by jquery. I really tested everything and I am not able to get tr element. Thank you for your help.
You can filter out the content of each TDs but honestly i don't see any purpose for that:
var someValue = 'someid="id303"';
$('table').find('td').contents().filter(function(){
return this.nodeType === 8 && this.nodeValue.indexOf(someValue) != -1;
}).closest('tr').css('background-color', 'red');
-jsFiddle-
If you need that string to setup something, then generally it is not a good practice to put that string in comment.
I would suggest you to put that someid as a data attribute in td element
<td data-someid="id301">...</td>
then you can access it by $td.attr("data-someid") or even use it in jQuery selector
$('td[data-someid="id301"]').css('background-color', 'green');
You can use jQuery Comments() Plug-in or
<input type="hidden" id="id301">
Try this:
<script>
var tableId = 'table1';
var table = document.getElementById(tableId);
var trs = table.getElementsByTagName('tr');
// Pattern for searching for the string like someid="id[somenumbersinarow]"
var pattern = /someid=\"id[0-9]+\"/
// Pattern for searching for numeric value
var numericPattern = /[0-9]+/
var innerHTML, tr;
for (var i = 0, amountOfTrs = trs.length; i < amountOfTrs; i++){
tr = trs[i];
innerHTML = tr.innerHTML;
/* Searching for the comment with "someid" string, turning it into string
(it will be the only string because there will be a single element in the array),
then again search for numbers, convert to string and try to parse it) */
console.log(parseInt(innerHTML.match(pattern).toString().match(numericPattern)));
}
</script>
This script properly works if there's only one comment per the TR element
pattern is a regular expression object. It can be used with modifiers such as g (search for ALL the matches in the text), for instance: /[0-9]+/g. In this case you'll get an array which may have a length greater than 1.
In the example I provided the modifier isn't used, so toString() method will return a string in this case. If you go further and try to get a number by another pattern, then you can use parseInt to extract number (id)
Be aware that if the match() method doesn't find anything it returns null, so before invoking function like in my example, you should either strongly know that this comment exists or perform some additional check.

How to parse formula of html table cell to acting like Excel, using Javascript

I am looking for a way to make html table acting like excel using Javascript (Jquery preferred). Here are my problem. I made a table like this:
<table>
<tr>
<td id="A1">10</td>
<td id="B1">10.5</td>
</tr>
<tr>
<td id="A2">5</td>
<td id="B2" formula="A1+B1+A2"></td>
</tr>
</table>
Every td has an id, some of those tds are added a formula attribute. And I wanna to calculate those formula, give the value of formula to the td.
In the table above, here, I wanna assign the B2 value 25.5(B2=A1+B1+A2).
Look like this:
<td id="B2" formula="A1+B1+A2">25.5</td>
Can anybody give me a clue? Thanks.
PS: Here are some resource that I found, but they do not solve my problem
Spreadsheet-like formulas on the DOM
http://zaach.github.com/jison/docs/
Thanks a lot #palindrom. I finally solved my problem based on your answer.
Here is my code:
$("td[formula]").each(function(){
//1 get formula attribute
var formula = $(this).attr('formula');
//2 use regex to make expression, with the surpport of "A122", "AB1" and more
var expression = formula.replace(/([A-Z]+[0-9]+)/g, "parseFloat(\$('#$1').html())") ;
//3 eval the expression
var result = eval( expression );
//4 set the value
$(this).html(result);
});
Should work for simple math, didnt try:
$("td[formula]").each( function() {
this.html( eval( this.attr("formula").replace(/[a-z][0-9]/g, "\$('#$0').html()") ) );
} );
Edit:
If you have functions like sum in the formulas, implement them as javascript functions and they should work too.
even if this too late, try this plugin https://github.com/xsanisty/jquery-calx
I have develop it using jison parser in its core, it will parse the formula in the data-formula attribute just like you want
This is a html table I wrote in which a formula is computed for each line (see iframe source).
The formula is written in JavaScript (as complex as can be) in which [abc] is replaced with the value of cell with id=abc (weights from the header) and {abc} with the text in cell from the same column in that line.
The columns are sortable
The weights are modifiable by the user and they are remembered in a cookie.
Hoping this can help.

jquery confusing code

I am learning Jquery and Javascript from web examples. I have a good working knowledge but some code still trips me up. The following code is used for a shopping cart to hide the check out button and replace with a div displaying a message about minimum cart requirements. There is a part of the code throwing me off though.
function getCollectionCount() {
var totalCollectionCount = 0;
var collection = $('td[alt*="Collection"]');
for (var i = 0; i < collection.length; i++) {
var curVal = $(collection[i]).find("select").val();
if (curVal != undefined){
totalCollectionCount += parseInt(curVal);
}
}
What does this part mean?
var collection = $('td[alt*="Collection"]');
td[alt*="Collection"] selects all <td> elements whose alt attribute contains Collection, such as:
<td alt="Collection"></td>
<td alt="CollectionFoo"></td>
<td alt="BarCollection12324343"></td>
but not
<td></td>
<td alt=""></td>
<td alt="Foo"></td>
Side note: this is a pretty basic question that could easily be answered by read the jQuery selectors API documentation:
element selector
attribute-contains selector
Please do try to research before you ask!
This is a jQuery attribute selector clause. It's selecting any td element which has an atrtibute named alt whose string contains the value Collection.
Contains Selector: http://api.jquery.com/attribute-contains-selector/
jQuery has a number of useful attribute selectors. Here is the main reference page for them. Very much worth the read if you're just getting started with jQuery
http://api.jquery.com/category/selectors/attribute-selectors/
That code returns every td element whose "alt" attribute contains "Collection".
http://api.jquery.com/attribute-contains-selector/
jQuery is full of these funky shortcuts that take forever to learn, so I always keep a copy of jQuery in action on my desk at all times :)
This code can be rewritten more simply and briefly like this:
function getCollectionCount() {
var totalCollectionCount = 0;
$('td[alt*="Collection"] select').each(function() {
var val = this.value || "0";
totalCollectionCount += parseInt(val, 10);
});
return(totalCollectionCount);
}
And, this is how it works:
Initialize totalCollectionCount to 0
Find all td elements that have the string "Collection" in the alt attribute and then find select elements within that td
Iterate over all elements found that match the above condition
Initialize a local variable with either the value of the select object or "0" if there is no value or it's empty
Turn that value into a number (must pass the radix to parseInt so it won't guess) and add it to the sub-total so far.
return the total we found.

Categories

Resources