2010-08-09 3 views
104

나는()과 같이 트림의 사용을 만드는 중이라서 : group_field 유형의 텍스트 입력 요소입니다IE8과 jQuery의 트림()

if($('#group_field').val().trim()!=''){ 

. 이것은 파이어 폭스에서 작동하지만 IE8에 그것을 시도 할 때 나에게이 오류 제공 :

Message: Object doesn't support this property or method 

나는 트림()를 제거하면, 그것은 IE8에서 잘 작동합니다. trim()을 사용하는 방식이 올바른지 생각했습니다. 어떤 도움

답변

201

에 대한 모든 대신이 시도

감사 :

if($.trim($('#group_field').val()) != ''){ 

추가 정보 :

+1

감사합니다. JQuery의 기능이 체인 가능하다고 생각했는데, 그것이 모두 작동하는 방식입니다. – Abs

+0

@Abs : 당신은 환영합니다 ... – Sarfraz

+38

@Abs :'val()'은 jQuery 객체를 반환하지 않으므로 연결이 불가능합니다. 문자열에 대해'trim()'메서드를 호출했지만 IE는'String.trim'에 대해 알지 못합니다. – janmoesen

15

당신은 $.trim, 리튬을 사용한다 이건 :

if($.trim($('#group_field').val()) !='') { 
    // ... 
} 
11

내가 아는 한, 자바 스크립트 문자열은 트림 방법이 없습니다. 이 기능 트림을 사용하려면 다음

<script> 
    $.trim(string); 
</script> 
+1

[w3schools에 연결하지 마십시오.] (http://www.w3fools.com/)! –

3

사용 jQuery를 입력 텍스트 트림 입력을 전체적으로 사용하여 다음

/** 
* Trim the site input[type=text] fields globally by removing any whitespace from the 
* beginning and end of a string on input .blur() 
*/ 
$('input[type=text]').blur(function(){ 
    $(this).val($.trim($(this).val())); 
}); 
10

또 다른 옵션은 실종 경우 String에 직접 메소드를 정의하는 것 :

if(typeof String.prototype.trim !== 'function') { 
    String.prototype.trim = function() { 
    //Your implementation here. Might be worth looking at perf comparison at 
    //http://blog.stevenlevithan.com/archives/faster-trim-javascript 
    // 
    //The most common one is perhaps this: 
    return this.replace(/^\s+|\s+$/g, ''); 
    } 
} 

다음 trim에 관계없이 브라우저의 작동합니다

var result = " trim me ".trim();