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

N

nboutelier

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
 
T

Thomas 'PointedEars' Lahn

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
 
R

RobB

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>
 
T

Thomas 'PointedEars' Lahn

micha said:
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.substring(document.getElementById('editorfenster').selectionStart,
document.getElementById('textarea_id').selectionEnd);
}
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.substring(0,
document.getElementById('textarea_id').selectionStart);
$after_replace =
document.getElementById('textarea_id').value.substring(document.getElementById('textarea_id').selectionEnd,
document.getElementById('textarea_id').value.length);
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;[email protected]&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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top