Reading text continuously from input using JavaScript
Contents |
Overview
This example demonstrates how to read text continuously from an input element in a web page by using JavaScript.
On some older devices, the property 'value' of an input element is not updated before the input element is blurred. This happens, for example, with the Nokia E51, version 400.34.011, with WebKit version 413.
On newer devices, this property is updated but no keyup event is obtained. This is why there is a periodical check for the value, and no onkeyup event listener is used.
On the Nokia N97, with WebKit version 525, the onkeyup event works fine.
Source: JavaScript
function init() {
debug('init');
addTextChangeListener(document.getElementById('textInput'), function (value) {
debug('textInputValueChanged to "'+value+'"');
});
}
window.onload = init;
function addTextChangeListener(textInput, callBack)
{
textInput._lastValue = textInput.value;
textInput._intervalId = -1;
textInput._callBack = callBack;
textInput.onchange = function () {
debug('onchange "'+this.value+'"');
}
textInput.onkeyup = function () {
debug('onkeyup "'+this.value+'"');
}
textInput.onkeydown = function () {
debug('onkeydown "'+this.value+'"');
}
textInput.onkeypress = function () {
debug('onkeypress "'+this.value+'"');
}
textInput._checkValueChanged = function () {
if ((this.value != "")
&& (this._lastValue != this.value)) {
this._callBack(this.value);
this._lastValue = this.value;
}
}
// Add a value check functionality when the filter text field receives focus.
textInput.onfocus = function ()
{
debug('onFocus');
var that = this;
this._intervalId = window.setInterval(function() {
// here, "this" would refer to something else than textInput...
that._checkValueChanged();
},250);
// 4 times in 1 second does not increase power consumption noticeably
};
// Remove the value check functionality when the filter text field loses focus.
textInput.onblur = function () {
debug('onBlur');
clearInterval(this._intervalId);
textInput._checkValueChanged();
};
}
var debugElement;
function debug(message)
{
if (!debugElement) {
debugElement = document.getElementById('debugList');
}
var subElement = document.createElement('li');
subElement.innerHTML = message;
debugElement.appendChild(subElement);
}
Source: Relevant HTML elements
<p>
<input id="textInput" type="text" ></input>
<!-- This example could be improved by hiding the button when everything is working ok -->
<input type="button" value="Read text!" ></input>
</p>
<ul id="debugList" style="font-size: x-small">
</ul>
Postconditions
Text is read periodically from the input element.
Supplementary material
The complete example page containing the examples discussed can be downloaded at File:Reading text continuously from input snippet.zip.
(no comments yet)