473,224 Members | 1,580 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,224 software developers and data experts.

Select/highlight a specific part of text string inside a form element

Scenario: you enter "foo bar" into a text field... Is it possible
through javascript to select/highlight just "foo"?

formObject.select()

selects all. I need to select only part of the string. -Nick

Jul 23 '05 #1
5 3247
nb********@hotmail.com wrote:
Scenario: you enter "foo bar" into a text field... Is it possible
through javascript to select/highlight just "foo"?
Yes.
formObject.select()

selects all. I need to select only part of the string.


0. Assign the value of the text field to a variable:

var myString = "foo bar";

1. Determine the start index of the substring in the value:

var startIndex = myString.indexOf("foo");

or use RegExps.

2. If the substring is contained in the value, determine the end index:

var endIndex = startIndex + "foo".length - 1;

3. Select text in text field from start to end index:

See the FAQ on how to use search engines on this topic.
HTH

PointedEars
Jul 23 '05 #2
function get_selection()
{
//$sel contains the marked text, can be empty
var $sel;

// ie
if(document.selection)
{
$sel = document.selection.createRange().text;
}
// mozilla
else
{
$sel =
document.getElementById('textarea_id').value.subst ring(document.getElementById('editorfenster').sele ctionStart,
document.getElementById('textarea_id').selectionEn d);
}
return ($sel);
}

function replace_selection($replace)
{
//replaces the marked text by $replace

// ie
if(document.selection)
{
document.getElementById('textarea_id').focus();
document.selection.createRange().text = $replace;
}
//mozilla
else
{
$before_replace =
document.getElementById('textarea_id').value.subst ring(0,
document.getElementById('textarea_id').selectionSt art);
$after_replace =
document.getElementById('textarea_id').value.subst ring(document.getElementById('textarea_id').select ionEnd,
document.getElementById('textarea_id').value.lengt h);
document.getElementById('textarea_id').value = $before_replace +
$replace + $after_replace;
}

Jul 23 '05 #3
nb********@hotmail.com wrote:
Scenario: you enter "foo bar" into a text field... Is it possible
through javascript to select/highlight just "foo"?

formObject.select()

selects all. I need to select only part of the string. -Nick


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">

//~~~~~~~~~~~~~~~~~

var selfields = // [,] 'field_name' : 'hilite_text'
{
'text1' : 'foo'
, 'text3' : 'bar'
}

//~~~~~~~~~~~~~~~~~

window.onload = function()
{
var regex, el, els = document.forms[0].elements; //first form
for (fname in selfields)
{
el = els[fname];
if (el.createTextRange
|| el.setSelectionRange)
{
el.regex = new RegExp('\\b' + selfields[fname] + '\\b');
el.onkeyup = el.onblur =
function()
{
selWord(this);
}
}
}
}

function selWord(obj)
{
var m = range = null;
if (m = obj.regex.exec(obj.value))
{
if (obj.createTextRange)
{
range = obj.createTextRange();
range.findText(m[0]);
range.select();
}
else if (obj.setSelectionRange)
{
obj.setSelectionRange(m.index, m.index + m[0].length);
obj.focus();
}
}
}

</script>
</head>
<body>
<form>
<input type="text" id="text1" name="text1" value=""> <small>no foo
!</small>
<br>
<input type="text" id="text2" name="text2" value="">
<br>
<input type="text" id="text3" name="text3" value=""> <small>no bar
!</small>
</form>
</body>
</html>

Jul 23 '05 #4
You guys are good! Thanks... exactly what I needed. -Nick

Jul 23 '05 #5
micha wrote:
function get_selection()
{
//$sel contains the marked text, can be empty
var $sel;

// ie
if(document.selection)
{
$sel = document.selection.createRange().text;
}
// mozilla
else
{
$sel =
document.getElementById('textarea_id').value.subst ring(document.getElementById('editorfenster').sele ctionStart, document.getElementById('textarea_id').selectionEn d);
}
return ($sel);
}

function replace_selection($replace)
{
//replaces the marked text by $replace

// ie
if(document.selection)
{
document.getElementById('textarea_id').focus();
document.selection.createRange().text = $replace;
}
//mozilla
else
{
$before_replace =
document.getElementById('textarea_id').value.subst ring(0,
document.getElementById('textarea_id').selectionSt art);
$after_replace =
document.getElementById('textarea_id').value.subst ring(document.getElementById('textarea_id').select ionEnd, document.getElementById('textarea_id').value.lengt h);
document.getElementById('textarea_id').value = $before_replace +
$replace + $after_replace;
}


Try to avoid using non-downwards-compatible features like
document.getElementById() when forms are involved. Therefore, and
for other reasons, the above should be rewritten (quick hack):

/**
* @argument number|string|HTMLFormElement f
* @argument number|string c
*/
function getFormControl(f, c)
{
var oControl = null;

if (typeof f != "undefined")
{
if (typeof f == "number" || typeof f == "string")
{
f = document.forms[f];
}

if (f)
{
var es = null;
oControl = (es = f.elements) && es[c];
}
}

return oControl;
}

var getSelection = function()
{
return null;
};

// IE
if (document.selection)
{
/**
* @argument number|string|HTMLFormElement f
* @argument number|string c
*/
getSelection = function(f, c)
{
var oControl = getFormControl(f, c);
if (oControl)
{
return document.selection.createRange().text;
}

return "";
};
}

// Mozilla
else
{
getSelection = function(f, c)
{
var oControl = getFormControl(f, c);
if (oControl)
{
return oControl.value.substring(
oControl.selectionStart,
oControl.selectionEnd + 1);
}

return "";
};
}

How to replace the selection was not required, however once I'm at it:

/**
* @author
* (C) 2003, 2004 Thomas Lahn &lt;ty******@PointedEars.de&gt;
* Distributed under the GNU GPL v2 and above.
* @optional Object|string o
* Object to be determined an method, i.e. a
* <code>Function</code> object assigned as property of
* another object. May also be a string to be evaluated
* and so is applicable to unknown properties.
* @return type boolean
* <code>true</code> if <code>o</code> is a method,
* <code>false</code> otherwise.
* @see #isMethodType()
*/
function isMethod(m)
{
var t;
(m = eval(m)) && (t = typeof m);
return (t == "function" || t == "object");
}

var replaceSelection = function()
{
return null;
};

// IE
if (document.selection)
{
/**
* @argument number|string|HTMLFormElement f
* @argument number|string c
* @argument string sReplacement
*/
replaceSelection = function(f, c, sReplacement)
{
var oControl = getFormControl(f, c);
if (oControl)
{
if (isMethod(oControl.focus))
{
oControl.focus();
}
document.selection.createRange().text = sReplacement;

return true;
}

return false;
}
}

// Mozilla
else
{
replaceSelection = function(f, c, sReplacement)
{
var oControl = getFormControl(f, c);
if (oControl)
{
var start = oControl.selectionStart;

oControl.value = oControl.value.replace(
new RegExp([
"((.|\n){", start, "})",
"(.|\n){", oControl.selectionEnd - start + 1, "}"
].join("")),
"$1" + sReplacement);

return true;
}

return false;
};
}
BTW: Even if JS allow variable identifiers to start with `$', it is not
required. These are script languages, but they are not shell script,
Perl or PHP. And you should reconsider your Pretty Printing style.
PointedEars
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: cgplays.com | last post by:
I have a select-pulldown at http://computergroupplays.com/fb-pres2.asp that changes the 3rd pulldown (Dbase) depending on what the user enters in the 2nd (Wk). My associate wants the values inside...
12
by: Kevin Lyons | last post by:
Hello, I am trying to get my select options (courses) passed correctly from the following URL: http://www.dslextreme.com/users/kevinlyons/selectBoxes.html I am having difficulty getting the...
15
by: lawrence | last post by:
Is this the correct way to test for a method before I use it? createRange() is, I believe, an IE only method. function wrapSelectionInTag(selection, tag) { if (document.selection.createRange)...
1
by: john woo | last post by:
Hi I'm not good at JS, but want to get more about it. I want to use a JSP (the java code just used to get date, the rest are html and javascript), to display a table. the requirement is the...
5
by: Atara | last post by:
I am trying to convert the following code to VB .Net, I still have some gaps (the lines that are marked with (*)) and also I need an ending condition for the while loop. any help would be...
4
by: praveen | last post by:
I have a form with treeview control loaded from xml document,text box, two buttons named "Find" and "FindNext" and my treeview which looks like below. Details |__ policy status |__ created by...
4
by: Matt Ratliff | last post by:
Hello, I would appreciate any assistance you have with the following problem: I have (as an example) an array of values as follows: arrayvalues=new Array("0001","0003","0005") where each is the...
3
by: trpost | last post by:
I want to be able to select a word when I highlight over any part of the word. When I say select the word, I want it to be highlighted as if I left clicked my mouse and dragged the cursor along the...
2
by: artev | last post by:
if I insert a string null in a select, it change position; why? I insert value "" in 2nd 3th select; <style type="text/css"> td {border:2px solid pink;}; </style>
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.