Javascript Limit Commas - javascript

I have a function that displays a countdown next to a text field for the number of characters in the field (think twitter)
<script language="javascript" type="text/javascript">
function countDown(control, maxLen, counter, typeName) {
var len = control.value.length;
var txt = control.value;
var span = document.getElementById(counter);
span.style.display = '';
span.innerHTML = (maxLen - len);
if (len >= (maxLen - 10)) {
span.style.color = 'red';
} else {
span.style.color = '';
}
}
</script>
And the next field down takes a comma separated value. Example:
tomato, apple, orange, pear
and I'd like to limit that list to 5 things (and 4 separating commas).
How can I make a similar function that counts down for the number of commas in the input.
I got this started, but it's not changing the value in the span.
my Javascript
<script language="javascript" type="text/javascript">
var max = 5;
function commaDown(area,ticker){
// our text in the textarea element
var txt = area.val();
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.val(txt.substring(0, lastComma));
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
</script>
and my html (I think the problem lies here)
<input id="choices" type="text" name="choices" class="text medium" onkeyup="commaDown('choices','limit');"/> <span id="limit">5</span><br/>
Any ideas?

Something like this (assuming you have a text field with id csv)
document.getElementById('csv').onkeydown = function(e){
if (!e) var e = window.event;
var list = this.value.split(',');
if (list.length == 5 && e.keyCode == '188' )
{
// what to do if more than 5 commas(,) are entered
// i put a red border and make it go after 1 second
this.style.borderColor ='red';
var _this = this;
setTimeout(function(){
_this.style.borderColor='';
_this.disabled=false;
},1000);
// return false to forbid the surplus comma to be entered in the field
return false;
}
}
example at http://www.jsfiddle.net/gaby/YEHXf/2/
Updated Answer
You seem to have mixed parts of jQuery in your code and that causes the script to fail
var max = 5;
function commaDown(_area, _ticker){
var area = document.getElementById(_area);
// our text in the textarea element
var txt = area.value;
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(_ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.value = txt.substring(0, lastComma);
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
live example at http://jsfiddle.net/z4KRd/

here is a solution:
test: http://jsbin.com/ulobu3
code: http://jsbin.com/ulobu3/edit
if you never used jsBin before, it is very easy, on the left side you have the javascript code (like if it was in your HTML code, and in your right side you have the html code.
and you just need to add /edit to the end of a jsbin url to edit that code, and save any new revisions to that code.
I added jQuery framework to make the example faster to code.

Related

How Facebook changes the Emoji from their symbols while chatting?

First Image - Initial Text when typing something in Facebook Chat Box
Second Image - The moment you hit space it converts to this!
I have seen in developer console it is not the input box at all, they are using span and all with background-image to do it but how to actually combine it completely, to avoid any clutter whatsoever. I am attaching a link of codepen of what I did when pressing Enter key. But not able to do for the Space Bar. Codepen Link Anything you guys can help. Thanks in advance. NOTE :- No external libraries and would prefer Javascript answer.
var emojiContainer = {
":)" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zeb/2/16/1f642.png",
"<3" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zed/2/16/2764.png"
};
var chatDetailText = document.getElementById('chatDetailText');
chatDetailText.addEventListener("keypress", function (e) {
console.log("Inside keypress event")
var textEntered = chatDetailText.value;
var keyPressed = e.which || e.keyCode;
console.log(emojiContainer[this.value])
if (keyPressed === 13){
console.log("inside keypress 13")
if(emojiContainer[this.value]){
console.log("inside value found of enter")
var emojiImg = document.createElement("img");
emojiImg.src = emojiContainer[this.value];
document.getElementById('enterPressed').appendChild(emojiImg);
document.getElementById('chatDetailText').value = '';
}else{
console.log("value not found of enter")
var divChatDetail = document.createElement('div');
/*chatDetailSeperator.className = "aClassName";*/ //To add class name for div
divChatDetail.innerHTML = this.value;
document.getElementById('enterPressed').appendChild(divChatDetail);
document.getElementById('chatDetailText').value = '';
}
}
}, false);
You can use HTML5 ContentEditable attribute for div.
here is just an example. Take care of cert position etc.
var emojiContainer = {
":)" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zeb/2/16/1f642.png",
"<3" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zed/2/16/2764.png"
};
var chatDetailText = document.getElementById('chatDetailText');
chatDetailText.addEventListener("keypress", function (e) {
console.log("Inside keypress event")
var textEntered = chatDetailText.innerHTML;
var keyPressed = e.which || e.keyCode;
console.log(keyPressed)
if (keyPressed === 32){
var last_word = textEntered.split(" ");
last_word = last_word[last_word.length-1];
console.log(last_word);
if(emojiContainer[last_word]){
console.log("inside value found of enter")
var emojiImg = "<img src='"+emojiContainer[last_word]+"' >";
textEntered = textEntered.replace(last_word, emojiImg)
chatDetailText.innerHTML = textEntered;
}
}
}, false);
<div id="enterPressed"></div>
<div contenteditable="true" id="chatDetailText" >edit this</div>
I got it done, thanks to Zeeshan for helping me with contenteditable. Do update if you have any improvisations.
var emojiContainer = {
":)" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zeb/2/16/1f642.png",
"<3" : "https://static.xx.fbcdn.net/images/emoji.php/v9/zed/2/16/2764.png"
};
var chatDetailText = document.getElementById('chatDetailText');
chatDetailText.addEventListener("keydown", function (e) {
//to perform the action based on pressing space bar (32) or enter (13).
var keydown = e.which || e.keyCode;
//to get the pointer location and modify to place to the end if needed
var selectionInfo = getSelectionTextInfo(this);
//to get the complete text extered by the user.
var input = chatDetailText.innerHTML;
//to cover the cases in which user enters <3 and gets interpreted as &lt
var textEntered = decodeHtml(input);
//To split the text entered and to get the location of the emoji for conversion
var last_word = textEntered.split(/\s{1}/);
//After splitting contains the emoji and now can be accessed.
last_word = last_word[last_word.length-1];
//space bar is pressed and the smiley is just inserted
if (keydown === 32 && selectionInfo.atEnd){
//if the emoji is available in our database, it'll replace the same using the Facebook url which is currently used.
if(emojiContainer[last_word]){
var emojiImg = "<img src='"+emojiContainer[last_word]+"' >";
textEntered = textEntered.replace(last_word, emojiImg);
chatDetailText.innerHTML = textEntered;
elemIterate = document.getElementById('chatDetailText');//This is the element to move the caret to the end of
setEndOfContenteditable(elemIterate);
}
//Enter key is pressed after typing the emoji
}else if (keydown === 13) {
// To avoid extra line insertion in div.
e.preventDefault();
//if the emoji is available in our database, it'll replace the same using the Facebook url which is currently used.
if(emojiContainer[last_word]){
var emojiImg = document.createElement("img");
emojiImg.src = emojiContainer[last_word];
var spanChatElement = document.createElement("span");
var precedingChatContent = textEntered.split(/\s{1}/);
precedingChatContent.pop(); //To pop the last smiley found
if(precedingChatContent.length !=0){
precedingChatContent = precedingChatContent.join(" ");
spanChatElement.innerHTML = precedingChatContent;
document.getElementById('enterPressed').appendChild(spanChatElement);
}
document.getElementById('enterPressed').appendChild(emojiImg);
document.getElementById('chatDetailText').innerHTML = '';
}else{
//If no Smiley found, just the plain text it'll automatically display the text in a div
var divChatElement = document.createElement('div');
//chatDetailSeperator.className = "aClassName"; To add class name for div
divChatElement.innerHTML = textEntered;
document.getElementById('enterPressed').appendChild(divChatElement);
document.getElementById('chatDetailText').innerHTML = '';
}
}
}, false);
function decodeHtml(html) {
var textAreaElement = document.createElement("textarea");
textAreaElement.innerHTML = html;
return textAreaElement.value;
}
//To send the pointer to the end of the div.
function setEndOfContenteditable(contentEditableElement){
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
//To check if it is at the end.
function getSelectionTextInfo(contentEditableElement) {
var atEnd = false;
var selectionRange, testRange;
if (window.getSelection) {
var windowSelection = window.getSelection();
if (windowSelection.rangeCount) {
selectionRange = windowSelection.getRangeAt(0);
testRange = selectionRange.cloneRange();
testRange.selectNodeContents(contentEditableElement);
testRange.setStart(selectionRange.endContainer, selectionRange.endOffset);
atEnd = (testRange.toString() == "");
}
}else if (document.selection && document.selection.type != "Control") {
selectionRange = document.selection.createRange();
testRange = selectionRange.duplicate();
testRange.moveToElementText(contentEditableElement);
testRange.setEndPoint("StartToEnd", selectionRange);
atEnd = (testRange.text == "");
}
return { atEnd: atEnd };
}
You just need to change the line if (keyPressed === 13){ to if (keyPressed === 32){ in your codepen link. And to stop that from posting the comment, you just need to add another function for if (keypressed === 13).

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

Find out the 'line' (row) number of the cursor in a textarea

I would like to find out and keep track of the 'line number' (rows) of the cursor in a textarea. (The 'bigger picture' is to parse the text on the line every time a new line is created/modified/selected, if of course the text was not pasted in. This saves parsing the whole text un-necessarily at set intervals.)
There are a couple of posts on StackOverflow however none of them specifically answer my question, most questions are for cursor position in pixels or displaying lines numbers besides the textarea.
My attempt is below, it works fine when starting at line 1 and not leaving the textarea. It fails when clicking out of the textarea and back onto it on a different line. It also fails when pasting text into it because the starting line is not 1.
My JavaScript knowledge is pretty limited.
<html>
<head>
<title>DEVBug</title>
<script type="text/javascript">
var total_lines = 1; // total lines
var current_line = 1; // current line
var old_line_count;
// main editor function
function code(e) {
// declare some needed vars
var keypress_code = e.keyCode; // key press
var editor = document.getElementById('editor'); // the editor textarea
var source_code = editor.value; // contents of the editor
// work out how many lines we have used in total
var lines = source_code.split("\n");
var total_lines = lines.length;
// do stuff on key presses
if (keypress_code == '13') { // Enter
current_line += 1;
} else if (keypress_code == '8') { // Backspace
if (old_line_count > total_lines) { current_line -= 1; }
} else if (keypress_code == '38') { // Up
if (total_lines > 1 && current_line > 1) { current_line -= 1; }
} else if (keypress_code == '40') { // Down
if (total_lines > 1 && current_line < total_lines) { current_line += 1; }
} else {
//document.getElementById('keycodes').innerHTML += keypress_code;
}
// for some reason chrome doesn't enter a newline char on enter
// you have to press enter and then an additional key for \n to appear
// making the total_lines counter lag.
if (total_lines < current_line) { total_lines += 1 };
// putput the data
document.getElementById('total_lines').innerHTML = "Total lines: " + total_lines;
document.getElementById('current_line').innerHTML = "Current line: " + current_line;
// save the old line count for comparison on next run
old_line_count = total_lines;
}
</script>
</head>
<body>
<textarea id="editor" rows="30" cols="100" value="" onkeydown="code(event)"></textarea>
<div id="total_lines"></div>
<div id="current_line"></div>
</body>
</html>
You would want to use selectionStart to do this.
<textarea onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"></textarea>
<div id="lineNo"></div>
<script>
function getLineNumber(textarea, indicator) {
indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
}
</script>
This works when you change the cursor position using the mouse as well.
This is tough because of word wrap. It's a very easy thing to count the number of line breaks present, but what happens when the new row is because of word wrap? To solve this problem, it's useful to create a mirror (credit: github.com/jevin). Here's the idea:
Create a mirror of the textarea
Send the content from the beginning of the textarea to the cursor to the mirror
Use the height of the mirror to extract the current row
On JSFiddle
jQuery.fn.trackRows = function() {
return this.each(function() {
var ininitalHeight, currentRow, firstIteration = true;
var createMirror = function(textarea) {
jQuery(textarea).after('<div class="autogrow-textarea-mirror"></div>');
return jQuery(textarea).next('.autogrow-textarea-mirror')[0];
}
var sendContentToMirror = function (textarea) {
mirror.innerHTML = String(textarea.value.substring(0,textarea.selectionStart-1)).replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br />') + '.<br/>.';
calculateRowNumber();
}
var growTextarea = function () {
sendContentToMirror(this);
}
var calculateRowNumber = function () {
if(firstIteration){
ininitalHeight = $(mirror).height();
currentHeight = ininitalHeight;
firstIteration = false;
} else {
currentHeight = $(mirror).height();
}
// Assume that textarea.rows = 2 initially
currentRow = currentHeight/(ininitalHeight/2) - 1;
//remove tracker in production
$('.tracker').html('Current row: ' + currentRow);
}
// Create a mirror
var mirror = createMirror(this);
// Style the mirror
mirror.style.display = 'none';
mirror.style.wordWrap = 'break-word';
mirror.style.whiteSpace = 'normal';
mirror.style.padding = jQuery(this).css('padding');
mirror.style.width = jQuery(this).css('width');
mirror.style.fontFamily = jQuery(this).css('font-family');
mirror.style.fontSize = jQuery(this).css('font-size');
mirror.style.lineHeight = jQuery(this).css('line-height');
// Style the textarea
this.style.overflow = "hidden";
this.style.minHeight = this.rows+"em";
var ininitalHeight = $(mirror).height();
// Bind the textarea's event
this.onkeyup = growTextarea;
// Fire the event for text already present
// sendContentToMirror(this);
});
};
$(function(){
$('textarea').trackRows();
});
This worked for me:
function getLineNumber(textarea) {
return textarea.value.substr(0, textarea.selectionStart) // get the substring of the textarea's value up to the cursor position
.split("\n") // split on explicit line breaks
.map((line) => 1 + Math.floor(line.length / textarea.cols)) // count the number of line wraps for each split and add 1 for the explicit line break
.reduce((a, b) => a + b, 0); // add all of these together
};
Inspired by colab's answer as a starting point, this includes the number of word wraps without having to introduce a mirror (as in bradbarbin's answer).
The trick is simply counting how many times the number of columns textarea.cols can divide the length of each segment between explicit line breaks \n.
Note: this starts counting at 1.

Make lines of text have equal length

In centered h1 elements, if the text falls on multiple lines, line breaks make the text look like this:
This is a header that takes up two
lines
This is a header that takes up three
lines because it is really, really
long
Is there a way to manipulate these elements so that the length of the lines of text is roughly equal? Like this:
This is a header that
takes up two lines
This is a header that takes
up three lines because it
is really, really long
The jQuery plugin Widow Fix prevents single-word lines, but I'm looking for something that evens out all the lines in a multi-line element. Are there any jQuery plugins for this, or can you recommend a strategy?
I would solve it using only strict JavaScript, going this way:
1. put a class named 'truncate' to h1 tags you want to break
2. configure the javascript code on your needs knowing that
MAXCOUNT: (integer) max chars counted per line
COUNT_SPACES: (boolean) white spaces must be counted?
COUNT_PUNCTUATION: (boolean) punctuation must be counted?
EXACT: (boolean) the last word must be cut?
BLOCKS_CLASS: (string) the className of the h1 to consider
I wrote the code very quickly so it must be better tested for bugs,
but it can be a starting point I think.
I'm not using jQuery in this code to keep the code light and to avoid dependencies.
I think I'm using all cross-browser commands (cannot test it I've got only linux now). However any correction for cross-browser compatibility task (included the use of jQUery if requested) might be easy.
Here is the code:
<html>
<head>
<style>
h1 {background-color: yellow;}
#hiddenDiv {background-color: yellow; display: table-cell; visibility:hidden;}
</style>
<script>
var MAXCOUNT = 20;
var COUNT_SPACES = false;
var EXACT = false;
var COUNT_PUNCTUATION = true;
var BLOCKS_CLASS = 'truncate';
window.onload = function ()
{
var hidden = document.getElementById('hiddenDiv');
if (hidden == null)
{
hidden = document.createElement('div');
hidden.id = 'hiddenDiv';
document.body.appendChild(hidden);
}
var blocks = document.getElementsByClassName(BLOCKS_CLASS);
for (var i=0; i<blocks.length; i++)
{
var block = blocks[i];
var text = block.innerHTML;
var truncate = '';
var html_tag = false;
var special_char = false;
maxcount = MAXCOUNT;
for (var x=0; x<maxcount; x++)
{
var previous_char = (x>0) ? text.charAt(x-1) : '';
var current_char = text.charAt(x);
// Closing HTML tags
if (current_char == '>' && html_tag)
{
html_tag = false;
maxcount++;
continue;
}
// Closing special chars
if (current_char == ';' && special_char)
{
special_char = false;
maxcount++;
continue;
}
// Jumping HTML tags
if (html_tag)
{
maxcount++;
continue;
}
// Jumping special chars
if (special_char)
{
maxcount++;
continue;
}
// Checking for HTML tags
if (current_char == '<')
{
var next = text.substring(x,text.indexOf('>')+1);
var regex = /(^<\w+[^>]*>$)/gi;
var matches = regex.exec(next);
if (matches[0])
{
html_tag = true;
maxcount++;
continue;
}
}
// Checking for special chars
if (current_char == '&')
{
var next = text.substring(x,text.indexOf(';')+1);
var regex = /(^&#{0,1}[0-9a-z]+;$)/gi;
var matches = regex.exec(next);
if (matches[0])
{
special_char = true;
maxcount++;
continue;
}
}
// Shrink multiple white spaces into a single white space
if (current_char == ' ' && previous_char == ' ')
{
maxcount++;
continue;
}
// Jump new lines
if (current_char.match(/\n/))
{
maxcount++;
continue;
}
if (current_char == ' ')
{
// End of the last word
if (x == maxcount-1 && !EXACT) { break; }
// Must I count white spaces?
if ( !COUNT_SPACES ) { maxcount++; }
}
// Must I count punctuation?
if (current_char.match(/\W/) && current_char != ' ' && !COUNT_PUNCTUATION)
{
maxcount++;
}
// Adding this char
truncate += current_char;
// Must I cut exactly?
if (!EXACT && x == maxcount-1) { maxcount++; }
}
hidden.innerHTML = '<h1><nobr>'+truncate+'</nobr></h1>';
block.style.width = hidden.offsetWidth+"px";
}
}
</script>
</head>
<body>
<center>
<h1 class="truncate">
This is a header that
takes up two lines
</h1>
<br>
<h1 class="truncate">
This is a header that takes
up three lines because it
is really, really long
</h1>
<br>
<h1>
This is a header pretty short
or pretty long ... still undecided
which in any case is not truncated!
</h1>
</center>
</body>
</html>
And here is a demo of that: http://jsfiddle.net/6rtdF/
Late to this party, but here's my approach. I get the initial element height (any elements with the class balance_lines, in the code below), then incrementally shrink the width of the element. Once the height of the element changes, I've gone too far. The step before that should have lovely roughly-equal line lengths.
$('.balance_lines').each(function(){
var currentHeight = $(this).height();
var thisHeight = currentHeight;
var currentWidth = $(this).width();
var newWidth = currentWidth;
// Try shrinking width until height changes
while (thisHeight == currentHeight) {
var testWidth = newWidth - 10;
$(this).width(testWidth);
thisHeight = $(this).height();
if (thisHeight == currentHeight) {
newWidth = testWidth;
} else {
break;
}
}
$(this).width(newWidth);
});
You can see this code in action on the homepage at apollopad.com.
The CSS Text 4 draft proposes text-wrap: balance, but I don't think any browser implements it yet.
In the meantime, you can use Adobe's jQuery plugin (demo): https://github.com/adobe-webplatform/balance-text

Implementing a javascript function to search in a div, getting textrange for the search

How do I get the textrange to do a search for a div (or a form)? Are there scripts already available, or jquery functions that search the text of a div?
I append a form to a div with this code:
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form"> </form>');
I'd like to have a search function that will only look for a string in that div. I specify the text range like this.
txt = window.document.body.getelementbyid(card_id).createTextRange();
The search function is one that I found on the net and that I am trying to update to search the div instead of the entire page. There will be several divs on the page and I want the search to be specific to each. I call that function from search_links(card_id);.
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
/* alert('search_links '+search_str); */
return search_linkcard(search_str, card_id);
}
var IE4 = (document.all);
var n = 0;
function search_linkcard(str, card_id) {
alert (card_id + ' ' + str);
var txt, i, found;
if (str == "")
return false;
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (IE4) {
txt = window.document.body.getelementbyid(card_id).createTextRange();
// Find the nth match from the top of the page.
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
}
// Otherwise, start over at the top of the page and find first match.
else {
if (n > 0) {
n = 0;
search_linkcard(str, card_id);
}
// Not found anywhere, give message.
else
alert("Not found.");
}
}
return false;
}
My specific questions are those at the beginning of the question: How do I specify a text range for the div? Is the syntax I have right? Are there scripts that already do what I want, i.e. search the contents of a specific div?
Did the search with :contains. Did not do one match at a time. Highlighted all matches.
// Open search
function open_search(card_id) {
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form" onclick="clear_search(\''+card_id+'\', this.form);"> </form>');
var frm_elements = frm_search_link.elements;
for(i=0; i<frm_elements.length; i++) {
field_type = frm_elements[i].type.toLowerCase();
switch (field_type)
{
case "text":
frm_elements[i].value = "";
break;
default:
break;
}
}
}
// Close search
function close_search(card_id, form) {
$('form.frm_search_links', $('#'+card_id)).remove();
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}
// Search links
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
var search_select = '.link:contains('+search_str+')';
var card_select = '#'+card_id;
var result = $(search_select,$(card_select)).addClass('search_results');
if (result.length == 0 || result.length == null) document.frm_search.linkcard_search_string.value = 'Not found.';
}
// Clear search
function clear_search (card_id, form) {
document.frm_search.linkcard_search_string.value = '';
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}

Categories