2023-09-29 200 View 공개 |
웹사이트나 블로그에서 게시물을 작성할 때, 카테고리에 따라 글의 형태나 내용을 다르게 입력해야 할 때 있습니다. 즉
먼저, 사용자에게 제공할 글의 형태를 선택할 수 있는 select 요소와 각 형태에 따라 동적으로 표시될 입력 필드를 구성합니다.
<select class='form-control' name='Contents_Type' id='contentsType'> <option value='0'>미선택</option> <option value='1'>사과</option> <option value='2'>복숭아</option> <!-- ... 중략 ... --> <option value='6'>수박</option> <!-- ... 후략 ... --> </select> <textarea name='CODE_Front_Expalin' id='codeFrontExplain' style="display:none;">
document.getElementById('selectOption').addEventListener('change', function() { let inputBox = document.getElementById('inputBox'); let textAreaBox = document.getElementById('textAreaBox'); // 초기 상태 설정 inputBox.style.display = 'none'; textAreaBox.style.display = 'none'; if (this.value === 'showInput') { inputBox.style.display = 'block'; } else if (this.value === 'showTextarea') { textAreaBox.style.display = 'block'; } });
위 예제에서는 <select> 요소에서 값을 선택하면 해당 값에 따라 <input> 또는 <textarea>가 표시되는 기능을 제공합니다. 기본적으로 두 요소는 display: none; 스타일로 숨겨져 있으며, 사용자가 특정 값을 선택하면 해당 요소가 display: block; 스타일로 변경되어 표시됩니다.