ExampleExecute a JavaScript when a user changes the selected option of a <select> element: <select onchange="myFunction()"> Try it Yourself » More "Try it Yourself" examples below. Definition and UsageThe onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on <select> elements. Browser Support
SyntaxIn JavaScript, using the addEventListener() method: object.addEventListener("change", myScript); Try it Yourself » Technical Details
More ExamplesExampleExecute a JavaScript when a user changes the content of an input field: <input type="text" onchange="myFunction()"> Try it Yourself »
functionRef는 예제HTML
JavaScript
결과명세
브라우저 호환성BCD tables only load in the browser 같이 보기01. onchange 함수 문법 <element onchange="myScript"> onchange 함수는 우리가 작성한 Javascript를 통해 변화가 일어났는지 탐지해줍니다. 예제 소스 <input type="text" value="hello" onchange="bgcolor_yellow(this)" /> <input type="text" value="world" onchange="bgcolor_yellow(this)" /> <script> function bgcolor_yellow(obj) { obj.style.backgroundColor = 'yellow'; } </script> 결과 02. onchange 함수 응용 예제 소스 <select id="TestSelect" name="SelectValue" onchange="chageLangSelect()"> <option value="" selected disabled>Choose your value</option> <option value="val01">YourValue01</option> <option value="val02">YourValue02</option> </select> <script> function chageSelectedValue(){ var yourTestSelect = document.getElementById("TestSelect"); // select element에서 선택된 option의 value가 저장됩니다. var selectedValue = yourTestSelect.options[yourTestSelect.selectedIndex].value; // select element에서 선택된 option의 text가 저장된다. var selectedText = yourTestSelect.options[yourTestSelect.selectedIndex].text; } </script> 9번 라인에서 'TestSelect'라는 아이디를 가진 element를 yourTestSelect에 저장합니다. 그리고 변경할 때 해당 element의 option 번째를 고른다면, 선택한 value와 text로 값이 변경되도록 하는 예제입니다. 여기서 var selectedValue와 selectedText는 크게 역할이 없습니다. 결과 |