I am making a chrome extension in which I want to do some string replacement in the text when the enter key is pressed in a focussed textarea. Here is the code snippet:
var elems = document.getElementById("ChatTabsPagelet").getElementsByTagName("textarea"),i;
matchClass = "uiTextareaAutogrow";
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')> -1) {
text = elems[i].value;
elems[i].onkeyup = function(evt) {
if(evt.keyCode == 13){
alert(elems[i].value);
}
};
}
}
Basically I am looking for all the textareas with the class uiTextareaAutogrow and I just want to access their values when the enter key is pressed in any of those textareas. However, I always get undefined in the alert box when I try the extension out on a webpage. I guess the keyup event is fired but it is not able to get a handle to the particular textarea. Where am I going wrong?
Note: I am keen on using javascript only(not jquery) as I want the extension to be really light.
The following example should do the trick! ( see a working JSFiddle here ).
You shouldn't use for..in
with array-like objects as the order cannot be guaranteed. Also when the value of an element is referenced in a dynamic function you need to use this.value
.
var elems = document.getElementsByTagName("textarea")
matchClass = "uiTextareaAutogrow";
for(var i = 0, n = elems.length; i < n; i++) { // <---- simple for loop
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')> -1) {
elems[i].onkeyup = function(evt) {
if(evt.keyCode == 13){
alert(this.value);
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.