0

Ok, I am writing some code which someone can use as a bookmarklet to jumble up an input box value in real time...

var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {

    elements[ii].addEventListener("keyup", function() {

        var input = elements[ii].value;
        var a = [""];
        var gen;
        for (x in input) {
            a[x] = input[input.length - x - 1];
        };
        for (x in a) {
            var gen = gen + a[x];
        };
        output = gen.replace('undefined', '');
        elements[ii].value = output;
    }, false);
};

This code (with JavaScript: in front) doesn't have affect on any input boxes. Can anyone see why?

Thanks!

David G
  • 94,763
  • 41
  • 167
  • 253
InfiniDaZa
  • 67
  • 12

2 Answers2

1

Use this instead of elements[ii] inside the addEventListener code. Cos elements[ii] will have no meaning inside that code.

LPD
  • 2,833
  • 2
  • 29
  • 48
1

I did a few fixes in your code. Here is the modified version:

var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {

    elements[ii].addEventListener("keyup", function() {

        var input = this.value;
        var a = [];
        var gen;
        for (var x in input) {
            a[x] = input[input.length - x - 1];
        };
        for (x in a) {
            var gen = gen + a[x];
        };
        output = gen.replace('undefined', '');
        this.value = output;
    }, false);
};

please check demo

closure
  • 7,412
  • 1
  • 23
  • 23
  • Now that I look at this again, other than the `undefined`, isn't all of this the same as `this.value = this.value.split('').reverse().join('');` – Paul S. Dec 15 '12 at 18:54
  • Yes, this is how you would reverse it. That was my first question. Your reverse logic is perfect. Besides, there is no need of 'undefined' check. There is nothing 'undefined' I have seen. – closure Dec 15 '12 at 19:32
  • If you saw no `undefined` when why did you do `output = gen.replace('undefined', '');`? This is because the _for..in_ is unfiltered; it includes all the enumerable properties on the object and it's prototype chain. – Paul S. Dec 15 '12 at 21:11