Nice programing

jQuery 확인

nicepro 2020. 11. 19. 22:03
반응형

jQuery 확인 존재하고 가치가 있음


다음 예가 있습니다.

<input type="text" class="input1" value="bla"/>

이 요소가 존재하고 하나의 명령문에 값이 있는지 확인하는 방법이 있습니까? 또는 적어도 그보다 짧은 것은

if($('.input1').length > 0 && $('input1').val() != '')

마일 길이의 조건으로 여기에서 좌절하고 있습니다.


입력이 존재하지 않으면 값이 없습니다. 이 시도...

if($('.input1').val())

다음과 같이 할 수 있습니다.

if($('.input1').length && $('.input1').val().length)

lengthfalse값이 인 경우 조건에서로 평가됩니다 0.


다음과 같이 할 수 있습니다.

jQuery.fn.existsWithValue = function() { 
    return this.length && this.val().length; 
}

if ($(selector).existsWithValue()) {
        // Do something
}

그냥 jQuery 코드에서 이것을 추적했습니다. .val () 함수는 현재 attributes.js 165 행에서 시작 합니다 . 내 주석이있는 관련 섹션은 다음과 같습니다.

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

따라서 undefined또는 ""또는 null-모두 if 문에서 거짓으로 평가됩니다.


고유 한 사용자 지정 선택기 :hasValue 를 만든 다음이를 사용하여 다른 jQuery 요소를 찾거나 필터링하거나 테스트 할 수 있습니다.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

그런 다음 다음과 같은 요소를 찾을 수 있습니다.

var data = $("form input:hasValue").serialize();

또는 다음을 사용하여 현재 요소를 테스트합니다. .is()

var elHasValue = $("#name").is(":hasValue");

jQuery.expr[':'].hasValue = function(el) {
  return el.value != "";
};


var data = $("form input:hasValue").serialize();
console.log(data)


var elHasValue = $("[name='LastName']").is(":hasValue");
console.log(elHasValue)
label { display: block; margin-top:10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <label>
    First Name:
    <input type="text" name="FirstName" value="Frida" />
  </label>

  <label>
    Last Name:
    <input type="text" name="LastName" />
  </label>
</form>

추가 읽기 :


if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{

    $('#user_inp').css({"font-size":"18px"});
    $('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
    $('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});

}

나는 다음과 같이 할 것 $('input[value]').something입니다. 이것은 가치가있는 모든 입력을 찾아서 뭔가를 작동시킵니다.

참고 URL : https://stackoverflow.com/questions/15481539/jquery-check-if-input-exists-and-has-a-value

반응형