jQuery : 필드 값이 null (비어 있음)인지 확인


답변:


170

필드의 값은 null 일 수 없으며 항상 문자열 값입니다.

코드는 문자열 값이 문자열 "NULL"인지 확인합니다. 대신 빈 문자열인지 확인하고 싶습니다.

if ($('#person_data[document_type]').val() != ''){}

또는:

if ($('#person_data[document_type]').val().length != 0){}

요소가 존재하는지 확인하려면 다음을 호출하기 전에해야합니다 val.

var $d = $('#person_data[document_type]');
if ($d.length != 0) {
  if ($d.val().length != 0 ) {...}
}

31
The value of a field can not be null, it's always a string value.이것은 전적으로 사실이 아닙니다. 나는 select포함하고있다 options. 내가 수행 할 때 .val()이에 반환 null. Jquery 1.7.2
Liam

@ Pispirulito : 나는 그렇게 생각하지 않으며, 그것이 바뀔 것이라고 생각하지 않습니다. select어떤없는 option요소는 당신이 일반적으로 가지고있는 것이 아닙니다. 꽤 쓸모가 없습니다.
Guffa 2014 년

@Guffa는 다른 점을 간청합니다. 빈 <select><option>어떤 종류의 유효성 검사에서 오는 사용자에게 가능한 옵션을 포함 할 수 있습니다 .
Malcolm Salvador

다음 솔루션을 사용하여에서 자리 표시자를 제공하는 경우 '사용 안 함'옵션이 선택 되었기 때문에 값으로 select시작됩니다 null. stackoverflow.com/questions/5805059/…
Sygmoral

37

또한 입력 필드를 다듬어 공백이 채워져 보이게 할 수 있습니다.

if ($.trim($('#person_data[document_type]').val()) != '')
{

}

14

가정

var val = $('#person_data[document_type]').value();

다음과 같은 경우가 있습니다.

val === 'NULL';  // actual value is a string with content "NULL"
val === '';      // actual value is an empty string
val === null;    // actual value is null (absence of any value)

따라서 필요한 것을 사용하십시오.


11

조건부로 전달하는 정보의 종류에 따라 다릅니다.

때때로 귀하의 결과는 null또는 undefined또는 ''또는 0일 것입니다. 간단한 유효성 검사를 위해 나는 이것을 사용합니다.

( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )

참고 : null! ='null'


6
_helpers: {
        //Check is string null or empty
        isStringNullOrEmpty: function (val) {
            switch (val) {
                case "":
                case 0:
                case "0":
                case null:
                case false:
                case undefined:
                case typeof this === 'undefined':
                    return true;
                default: return false;
            }
        },

        //Check is string null or whitespace
        isStringNullOrWhiteSpace: function (val) {
            return this.isStringNullOrEmpty(val) || val.replace(/\s/g, "") === '';
        },

        //If string is null or empty then return Null or else original value
        nullIfStringNullOrEmpty: function (val) {
            if (this.isStringNullOrEmpty(val)) {
                return null;
            }
            return val;
        }
    },

이를 달성하기 위해이 도우미를 활용하십시오.


이 거의 같아 isStringNullOrEmptyIS isStringFalsey때문에 return !val;일 것이다
마크 Schultheiss에게

0

jquery는 val()기능과 not value(). jquery를 사용하여 빈 문자열을 확인할 수 있습니다.

if($('#person_data[document_type]').val() != ''){}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.