본문 바로가기

JavaScript

select 태그에서 option 선택 값 바뀔 때마다 이벤트 걸기 (on change)

사용자가 select 태그에서 상위 카테고리의 값을 선택할 때마다

하위 카테고리의 목록이 바뀌도록 이벤트를 주려고 한다.

select 태그가 갖는 onchange라는 요소를 추가하려고 했다.
하지만 값이 함수로 안 가고 문자열로 바뀌어서 들어갔다.

 

let testch = function() {
                alert('change1');
            }
let sel = document.querySelector('#sales_type');
sel.setAttribute('onchange', testch);

//결과
<select id="sales_type" onchange="function() {
    alert('change1');
    }">



함수를 직접 주지 않고, 함수 이름만 전달하기로 했다.
그러면 그 이름을 갖는 함수를 script에서 찾아서 실행할 것이다.
아래처럼 하니 정상적으로 함수가 실행됐다.

let sel = document.querySelector('#sales_type');
let testch = function() {
        alert('change1');
    }
sel.setAttribute('onchange', "testch()");

//결과
<select id="sales_type" onchange="testch()">



아래와 같이 객체처럼 접근해서 직접 지정해 줄 수도 있다.
이렇게 하면 select 태그 자체에는 변화가 없다.
다만 해당 select 의 Event Listener 안을 들여다 보면 
change 이벤트에 우리가 넣어 준 함수가 들어 있는 것을 알 수 있다.

let testch = function() {
        alert('change1');
    }
let sel = document.querySelector('#sales_type');
sel.onchange = testch;

//위와 아래는 같은 내용

let sel = document.querySelector('#sales_type');
sel.onchange = function() {
            alert('change2');
        };

//결과
<select id="sales_type">



javaScript의 addEventListener 함수를 이용해도 된다. 

let sel = document.querySelector('#sales_type');
sel.addEventListener('change', testch);

//위와 아래는 같은 내용

document.querySelector('#sales_type').addEventListener('change', function() {
            alert('change2');
        });

220401

 

참고 자료
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener

반응형