473,386 Members | 1,817 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,386 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 3258
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.