0

I have an input box that onpropertychange="validateEntryIE(this)"

validateEntryIE = function(object) {
    $(object).val(validateEntry($(object).val()));
}

Which calls:

validateEntry = function(str) {
    if( str != "" ) {
        var regx = /[A-Za-z0-9_]/;
        var str_new = "";
        var chars = str.split('');
        for(var i in chars) {
            if (regx.test(chars[i])) {
                str_new += chars[i];
            }
        }
        return str_new;
    }
}

However it does not replace the value and only returns a stack overflow. I am stuck beyond all belief. Does anyone know what has caused this and how to rectify

Charabon
  • 737
  • 2
  • 11
  • 23
  • 4
    Just to verify, you're using the jQuery 1.x line? 2.x versions do not support ie8. – furydevoid Aug 13 '14 at 13:17
  • 1
    @RabNawaz, using an empty string with split will split a string into a character array. Though OP does not need to do it as they could just use a regular for loop and use the iterator as an index on the string – Patrick Evans Aug 13 '14 at 13:19
  • @RabNawaz str.split('') indicates split on every character and I am using 1.10.2 – Charabon Aug 13 '14 at 13:21
  • 3
    Also, you could alternatively just do ```str.replace(/[^A-Za-z0-9_]/g, '');``` instead of that fancy split & loop. – furydevoid Aug 13 '14 at 13:22
  • Do not use `for ... in` loops to iterate through arrays. Use `for (var i = 0; i < chars.length; ++i)` instead. – Pointy Aug 13 '14 at 13:22
  • Note that `for in` to loop over arrays is not a good practice...see http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea. Also, as @PatrickEvans pointed out, you could just loop over the string itself in this case, e.g. `for (var i=0; i – Matt Browne Aug 13 '14 at 13:23
  • @furydevoid Why don't you post that as an answer? – Matt Browne Aug 13 '14 at 13:25
  • @MattBrowne I've got a few tips, but I'm not 100% sure what's causing the actual issue. No worries, though. =) – furydevoid Aug 13 '14 at 13:27
  • @MattBrowne Thats not the issue I'm having, Its just an improvement to the replace ... and the reason for doing it this way is because if it doesnt match I log the character for messages etc. – Charabon Aug 13 '14 at 13:27

1 Answers1

4

You are getting a stack overflow because of this

onpropertychange="validateEntryIE(this)"

It will get called each time you set the value of the input box, and since the function itself changes the property it then ends up causing itself to be called again, and again and again... repeatedly till you get the stack overflow.

Try using either the onkeyup, onblur, or onchange events instead so that you do not get a recursion.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87