sourcecode

jQuery - 입력 요소가 텍스트 상자인지 선택 목록인지 확인합니다.

copyscript 2023. 10. 16. 22:01
반응형

jQuery - 입력 요소가 텍스트 상자인지 선택 목록인지 확인합니다.

jQuery에서 :input filter로 반환되는 요소가 텍스트 상자인지 선택 목록인지 확인하려면 어떻게 해야 합니까?

각각에 대해 다른 동작을 취하고자 합니다(textbox는 텍스트 값을 반환합니다, select는 키와 텍스트를 모두 반환합니다).

예제 설정:

<div id="InputBody">
<div class="box">
    <span id="StartDate">
        <input type="text" id="control1">
    </span>
    <span id="Result">
        <input type="text" id="control2">
    </span>
    <span id="SelectList">
        <select>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
    </span>
</div>
<div class="box">
    <span id="StartDate">
        <input type="text" id="control1">
    </span>
    <span id="Result">
        <input type="text" id="control2">
    </span>
    <span id="SelectList">
        <select>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
    </span>
</div>

그리고 대본은 다음과.

$('#InputBody')
    // find all div containers with class = "box"
    .find('.box')
    .each(function () {
        console.log("child: " + this.id);

        // find all spans within the div who have an id attribute set (represents controls we want to capture)
        $(this).find('span[id]')
        .each(function () {
            console.log("span: " + this.id);

            var ctrl = $(this).find(':input:visible:first');

            console.log(this.id + " = " + ctrl.val());
            console.log(this.id + " SelectedText = " + ctrl.find(':selected').text());

        });

이렇게 할 수 있습니다.

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

더 느리지만 더 짧고 깨끗한 이것.

if( ctrl.is('input') ) {
    // it was an input
}

좀 더 구체적으로 알고 싶다면 다음과 같은 유형을 테스트할 수 있습니다.

if( ctrl.is('input:text') ) {
    // it was an input
}

또는 다음을 사용하여 DOM 속성을 검색할 수 있습니다..prop

여기 select box의 샘플 코드가 있습니다.

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

텍스트 상자용

  if( ctrl.prop('type') == 'text' ) { // for text box }

종류만 확인하고 싶다면 jQuery의 .is() 함수를 사용하면 됩니다.

아래에 사용했던 것처럼

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

다음 코드를 사용하여 양식 요소가 입력인지 선택인지 확인할 수 있습니다.

$('ElementSelector').prop('tagName').toLowerCase();

언급URL : https://stackoverflow.com/questions/5108337/jquery-determine-if-input-element-is-textbox-or-select-list

반응형