This question already has answers here:
Highlight a word with jQuery
(13 answers)
Closed 5 years ago.
I'm trying to implement a search for a table, I found an answer on the web and I tried it out, it works fine!
now I want to highlight (change text colour: text colour class = blue-text) that search keyword found in a table cell, I searched for this answer but I didn't find anything helpful!
my HTML is
<table class="stdtable">
<tr>
<td id="stdname">Name</td>
<td id="stdreg">Reg. No.</td>
<td id="stdparent">Parent</td>
<td id="stdgrp">Group</td>
<td id="action">Action</td>
</tr>
</table>
and Jquery is
$("#filter").on("keyup", function() {
var searchKey = $(this).val().toLowerCase();
$(".stdtable tr #stdname").each( function() {
var searchStr = $(this).text().toLowerCase();
if (searchStr.indexOf(searchKey)!=-1) {
$(this).parent().show();
}
else {
$(this).parent().hide();
}
});
});
how can I highlight the searched text?
if I search N the text N in Name should change the colour
and if I clear the search field I need to clear colour of the text also
I don't know the setup you have, but I would make a class "highlighted"
and give this class the property: color: blue; or whatever any other css properties you want for the special results.
then
$("#stdname").addClass("highlighted");
and
$("#stdname").removeClass("highlighted");
when you remove the search field
Edit: Leaving the above for someone that wants all the text.
You could take
var s = $(this).val();
var txt = $("#stdname").val().replace(s, '<span style="color: blue">' + s + '</span>');
$("#stdname").val(txt);
please note, you are going to end up with strange behavior if you don't strip the span statement from $("#stdname").val() every time a key is up
Related
This question already has answers here:
How do I select text nodes with jQuery?
(12 answers)
Closed 8 years ago.
Is it possible to use JQuery to hide the input elements plus the text after the input? The code is generated, so I cannot change the text, wrap it in a span or alter it in any way.
<label>Event Location <span class="req">*</span></label><br>
<input type="radio" name="a22" id="a22_0" value="Lafayette LA">Lafayette LA<br>
<input type="radio" name="a22" id="a22_1" value="Houston TX">Houston TX<br>
<input type="radio" name="a22" id="a22_3" value="San Antonio TX">San Antonio TX
You need to iterate the parent elements (TDs in your example added as an answer), find all the text elements that follow a radio button, then wrap them in hidden spans:
e.g.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6gzfLorp/3/
$('td').contents().each(function (e) {
if (this.nodeType == 3 && $(this).prevAll(':radio').length) {
$(this).wrap($('<span>').hide());
}
});
Note: Your question is a little ambiguous, but it would appear from your answer you have TDs which you could just hide all contents of the TD using:
http://jsfiddle.net/TrueBlueAussie/6gzfLorp/7/
$('.set-cities td').each(function (e) {
$(this).contents().wrapAll($('<span>').hide());
});
It is wrapped in a td tag. Here's what I have for now:
$("label:contains('Event Location')").parent("td").wrap("<span class='set-cities'></span>");
$('.set-cities').empty();
$('.set-cities').append("<td><label>Event Location <span class='req'>*</span></label><br><input type='radio' name='aa2' id='aa2_1' value='Houston TX' checked='checked'>Houston TX<br></td>");
I just going to change the whole block of text rather than just the city name.
In case you wanted to replace the text node directly, here's a way to do it. I borrowed from https://stackoverflow.com/a/298758/728393 and tailored it to your situation
function replaceTextAfter(selector,newtext){
var textnode = $(selector).parent().contents() // we need to contents as a collection
.filter(function(){
return this.nodeType == 3 && $(this).prev().is($(selector)); //return true if node is text and the previous node is our selector
});
textnode[0].data = newtext; //change the text
}
replaceTextAfter('#a22_0','abc');
http://jsfiddle.net/z606no23/
Thi delete all text after an element done, until a new tag
http://jsfiddle.net/alemarch/hm7ey6t5/
function deleteElemPlusText( elem ) {
var contestoHtml = $(elem).parent().html()
var thisHtml = $(elem).get(0).outerHTML // $(elem).outerHTML()
var re = new RegExp(thisHtml + "([^<])*")
var newContesto = contestoHtml.replace(re, "")
$(elem).parent().html(newContesto)
}
function deleteAllElemsPlusText( toDelete ) {
var x = $(toDelete).length;
for (var i = 0; i < x; i++) {
deleteElemPlusText($(toDelete).eq(0))
}
}
deleteAllElemsPlusText( "input[type=radio]" )
note: not all browser have outerHTML properties access, but you can use this jquery plugin http://www.darlesson.com/jquery/outerhtml/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to Javascript and am struggling with how it all actually works. I can't seem to find an answer to this question.
I've created a table and given each table cell a unique ID. I've also given each cell it's own background colour with css. Using Javascript, how can I find out what the background colour is for each cell? How do I actually access that property of each cell?
Thanks
Dave
There are two parts to this:
Getting the element
Getting the color assigned to it
Getting the element
If you know the cell ID, you can use document.getElementById:
var element = document.getElementById("the-id");
If you want to do this in response to an event that happens on the cell, for instance a click, you can use an event handler. For instance, suppose the table has the id "my-table":
document.getElementById("my-table").addEventListener("click", function(event) {
var element = event.target;
while (element && element.tagName !== "TD") {
if (element === this) {
// No cell was clicked
return;
}
element = element.parentNode;
}
// ...use element here
});
That hooks the click event on the table (so you don't have to hook it on every single cell), then when the click reaches the table, finds the td that the click passed through on its way to the table (if any).
Note: Old versions IE (IE8 and earlier) don't have addEventListener, they have Microsoft's predecessor to it, attachEvent. This answer shows how to work around that if you need to.
Getting the color
If you assigned the color directly on the element, via the style attribute (<td style="color: ..."...), you can use the style object on the element:
var color = element.style.color;
If it's assigned via a stylesheet, that won't work, you need to use getComputedStyle instead:
var color = getComputedStyle(element).color;
Again, old versions of IE are a pain in this regard, they don't have getComputedStyle but they do have a currentStyle property on elements, so you can polyfill (shim) getComputedStyle:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudo) {
if (typeof pseudo !== "undefined") {
throw "The second argument of getComputedStyle can't be polyfilled";
}
return element.currentStyle;
};
}
Example
Here's an example (modern browsers only) where you click a cell to get its color:
// Hook click on the table
document.getElementById("my-table").addEventListener("click", function(event) {
var element = event.target;
while (element && element.tagName !== "TD") {
if (element === this) {
// No cell was clicked
return;
}
element = element.parentNode;
}
// Show the color
alert("Color: " + getComputedStyle(element).color);
}, false);
.foo {
color: red;
}
.bar {
color: green;
}
.biz {
color: blue;
}
.baz {
color: #880;
}
<table id="my-table">
<tbody>
<tr>
<td class="foo">foo</td>
<td class="bar">bar</td>
</tr>
<tr>
<td class="biz">biz</td>
<td class="baz">baz</td>
</tr>
</tbody>
</table>
I want to add a class (and later on to send that string to php) to a text with javascript. Whenever I try to do that, the code is adding the class to the first occurrence of my selection, not to the actual selection. Keep in mind that I want to send that EXACT selection to php (and put it in a database as well so it keep that class even after refresh).
JQ
$("#highlight").click(function(){
paraval = $('#para').html();
sel = window.getSelection();
newst = '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(sel, newst);
$('#para').html(newvalue);
});
HTML
<p>Will only highlight if text is selected from comment class div only</p>
<div class="comment" id="para" contenteditable="true">Here goes some text Here goes some text Here goes some text Here goes some text
Some other text</div>
<input type="button" value="Highlight" id="highlight"/>
CSS
.selectedText{
background-color:yellow;
}
.comment{
border: solid 2px;
}
.comment::selection {
background-color: yellow;
}
example here: http://jsfiddle.net/zq1dqu3o/3/
try to select the last occurrence of the word "text". the first one will get the class "selectedText"...
thanks
Call me lazy, but if you don't mind span being you selection marker tag, you can use rangy's cssApplier class.
var cssApplier;
$(document).ready(function() {
rangy.init();
cssApplier = rangy.createCssClassApplier(
"selectedText", {normalize: true,
applyToEditableOnly:true});
});
$("#highlight").click(function(){
if(cssApplier != undefined)
{
cssApplier.toggleSelection();
}
});
I use applyToEditableOnly here to make it only work in that specific div. (I'm not sure how cross-browser compatible that particular setting is. Worked in Chrome and Firefox though.) This uses position rather than selection text to decide what to mark.
JS Fiddle Here: http://jsfiddle.net/zq1dqu3o/7/
You can get the last occurence with lastIndexOf() and proceed like this:
$("#highlight").click(function(){
paraval = $('#para').text();
sel = "text";
var n = paraval.lastIndexOf(sel);
var before = paraval.substring(0,n);
newst = before + '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(paraval, newst);
$('#para').html(newvalue);
});
Just created a fiddle for it: Replacing last occurence
Note: This quick example is only working because the word you want to highlight is at the last position of the text, but you can check out if this solution is ok for your request. In case the last occurence of the word is elsewhere, just create a variable "after" that contains the text following the last occurence of the word to the end.
Have just provided an example for this in updated fiddle: Replacing last occurence update
with following update to previous code:
var after = paraval.substring(n + sel.length, paraval.length);
newst = before + '<a class="selectedText">' + sel + '</a>' + after;
If i mouse over a TD element i want to highlight part of the string in another TD. Example: If i mouse over apple i want to highlight the apple part of applebanana.
I tried several things but didn't get closer to any solution. Thank you for your help.
My Code up to now: Cannot use word param because it is undefined. this.innerText does not return "apple".
Also onMouseout the hightlighted part of the string gets deleted.
function hightlightInput(word){
$(document.getElementById("testid")).html($(document.getElementById("testid")).html().replace(new RegExp("(apple)(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>"));
}
function resetHighlight() {
$(document.getElementById("testid")).find("mark").replaceWith(function() {
return $(document.getElementById("testid")).contents();
});
}
HTML
<table>
<tr>
<td onMouseOver="hightlightInput(this.innerText)"onMouseOut="resetHighlight()">apple</td>
<td id="testid">applebanana</td>
</tr>
</table>
In these situations, I always use a regexp and put the text in a <mark> element, which I remove later on.
You could then improve it by giving colors in and adding these as a style to the mark element, but by default it gives a yellow background to text (in most browsers). The mark element is easy to find back and usually doesn't get used for anything else, so its perfect for these things.
HTML:
<table>
<tr><td id="change">applebanana</td></tr>
<tr><td onMouseOver="highlightInput(this, this.textContent)"onMouseOut="resetHighlight(this)">apple</td></tr>
</table>
Here's a solution fully in native JS:
function highlightInput(element, word) {
element.innerHTML = element.innerHTML.replace(new RegExp("(" + word + ")(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>");
}
function resetHighlight(element) {
var marks = element.getElementsByTagName("mark");
var marksLength = marks.length;
for(var i = (marksLength - 1); i >= 0; --i)
{
element.replaceChild(document.createTextNode(marks[i].innerText), marks[i]);
}
}
Fiddle: http://jsfiddle.net/gpgekko/LshW6/1/
Here's a solution using the jQuery library:
function highlightInput(element, word) {
$(element).html($(element).html().replace(new RegExp("(" + word + ")(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>"));
}
function resetHighlight(element) {
$(element).find("mark").replaceWith(function() {
return $(this).contents();
});
}
Fiddle: http://jsfiddle.net/gpgekko/LshW6/
I'll leave the adaptation to find all elements to highlight up to you, let me know if you need help with that. But it's probably just looking through the table for occurrences of the word if I read your question correctly.
I'm trying to select an element from my HTML code, to then use it in JavaScript (it needs to be highlighted). The HTML consists of a table with 36 td's.
My code so far:
var box;
function getRandom()
{
return (Math.floor(Math.random()*37))
}
function highlight()
{
box = document.getElementById(getRandom());
box.style.backgroundColor = "yellow";
}
If anyone can give me any pointers, it'd be appreciated. I know it would be easy using jQuery, but I haven't begun learning that yet.
Edit: excerpt of the HTML code, this goes up to name="36".
<table id="reflexTable">
<tbody>
<tr>
<td name="1"></td>
<td name="2"></td>
<td name="3"></td>
<td name="4"></td>
<td name="5"></td>
<td name="6"></td>
</tr>
A nicer way that does not involve setting element ids:
function highlight() {
// get all TDs that are descendants of table#reflexTable:
var tds = document.getElementById('reflexTable').getElementsByTagName('td');
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight td at that index
tds[rand].style.backgroundColor = "yellow";
}
The big advantage of this method is that you can add/remove as many TDs as you please without needing to edit your JS to generate a valid random number.
getElementById gets the element which has the matching id. Your table data cells don't have an id at all. They have a name, but HTML doesn't allow that.
Switch to id.
HTML 4 doesn't allow an id to start with a number. Prefix the id with a common string. Then:
document.getElementById("foo" + getRandom());
You're not setting the id attribute, you're setting the name attribute, change it to:
<td id="1"></td>
...etc
Several things:
You should declare the box variable inside the highlight function.
You have to convert that random number to a string.
Quentin mentioned something important--you should give each table element an id of something like "s0","s1","s2", etc...
Start the naming at 0 because your getRandom function will sometimes return it.
function highlight(){
var number;
number = getRandom().toString();
var box;
box = document.getElementById("s" + number);
box.style.backgroundColor = "yellow";
}