1

I'm getting this error in IE8 and IE7 for some reason. I'm looping through all keys within my object and it keeps telling me Object doesn't support this property or method on this on:

var inVal = $(inType + "#" + inName).val().trim();

The entire block is below:

for (var key in inputs) { // find all keys "brand", "name", etc. in our inputs object
        var errors = false;

        if (inputs.hasOwnProperty(key)) { // focus on our obj. not all others on page 
            var inType = inputs[key].inputType;
            var inName = inputs[key].inputName;
            var inVal = $(inType + "#" + inName).val().trim(); // construct input field

            if (inVal == '' || inVal == null) {
                errors = true;

                $('#' + inName + '-error').html('');
                $('#' + inName + '-error').hide().fadeIn().html(inputs[key].errorMsg);
                $(inType + '#' + inName).focus();
                $('#modal-loadable-inner').scrollTop(inputs[key].scrollTop);

                return;
            } else { // user corrected error
                errors = false;
                $('#' + inName + '-error').html(''); // remove error txt
            }
        }
    }

Someone posted this on Doug Crockford's jslint boards and he responded with:

for (key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { ... } }

hasOwnProperty should have been an operator, not a method, because being a method, it is prone to these sorts of problems. But it is what it is, so you have to work around that.

Works fine in Chrome, FF, Safari, Opera, etc.. as usual. Any idea on a workaround?

bob_cobb
  • 2,229
  • 11
  • 49
  • 109

2 Answers2

4

I think it's caused by your trim() as string do not have this method.

Try this instead

var inVal = $.trim($(inType + "#" + inName).val());
Quincy
  • 4,393
  • 3
  • 26
  • 40
  • I think you have it. *val* should return a string, and not all browsers have a *String.prototype.trim* method (such as IE 8). – RobG Nov 16 '11 at 02:52
  • @RobG The [jQuery `.val()` documentation](http://api.jquery.com/val/) says that it can return a "String, Number, Array". So it's not 100% correct to say that `.val()` _always_ returns a string. – GregL Nov 16 '11 at 05:35
  • Your right, it might return an array if the element is a multiple select element. It should never return a number, can you say when it does? – RobG Nov 16 '11 at 09:12
1

.val() may not be returning a string, so calling .trim() on it is probably causing the problem. Try using an intermediate variable and checking it is not undefined before calling .toString().trim() on it (assuming .trim() is a method you added to strings in Javascript - the jQuery method is $.trim()).

GregL
  • 37,147
  • 8
  • 62
  • 67