본문 바로가기
Coding With Jina/JavaScript

[자바스크립트] value의 값이 변경 되었을 때 발생하는 이벤트 - change

by 진아리♡ 2021. 1. 17.
728x90
반응형

 

 

change

- change는 폼 컨트롤(value의 값)의 값이 변경 되었을 때 발생하는 이벤트

- input(text,radio,checkbox), textarea, select 태그에 적용

 

 

element.addEventListener("change",function( ));

 

 

select 선택지를 변경해서 선택하면 그 선택한 value 값을 로컬 스토리지에 저장하는 로직

 

HTML
<body>
    <h1>Where are you from?</h1>
    <form class="js-form">
        <select>
            <option value="null">--- Choose Your Country ---</option>
            <option value="Korea">Korea</option>
            <option value="Greece">Greece</option>
            <option value="Turkey">Turkey</option>
            <option value="Finland">Finland</option>
        </select>
    </form>

    <script src="gretting.js"></script>
</body>

 

자바스크립트
const LOCALSTORAGE_KEY = "country",
        form = document.querySelector(".js-form"),
        select = form.querySelector("select");


form.addEventListener("change",saveCountry);

function saveCountry(){
    localStorage.setItem(LOCALSTORAGE_KEY, select.value);
}

function loadCountry(){
    const currentSelect = localStorage.getItem(LOCALSTORAGE_KEY);
    if(LOCALSTORAGE_KEY !== null){
        select.value = currentSelect;
    }
}

function init(){
    loadCountry();
}

init();
728x90
반응형