JavaScript
[jquery] Select 박스에서 '직접 입력' 옵션으로 입력란 토글하기: 표시와 숨김 기능 구현
trueman
2024. 7. 24. 11:36
728x90
728x90
Select 박스에서 '직접 입력' 옵션으로 입력란 토글하기
1. html
<tr>
<th>형식</th>
<td>
<select id="selectBox">
<option value="">선택</option>
<option value="1">1번</option>
<option value="2">2번</option>
<option value="3">3번</option>
<option value="4">4번</option>
<option value="5">5번</option>
<option value="direct">직접 입력</option>
</select>
<input type="text" id="inputText" name="type" value="" maxlength="80" />
</td>
</tr>
2. js
function syncInputWithSelect() {
// select 박스의 첫번째 option 값으로 초기화
var selectBox = $("#selectBox");
selectBox.val(selectBox.find('option:first').val());
// input 태그의 값
var inputValue = $("#inputText").val();
var matchFound = false;
// option 수만큼 'each' 루프
$("#selectBox option").each(function(index) {
/* input 값과 select 박스의 option 값이 같은 경우
* 해당 option 값으로 selected
* matchFound = true
*/
if($(this).val() == inputValue) {
selectBox.prop('selectedIndex', index);
matchFound = true;
return false;
}
});
// (1) input 값과 select박스 값이 같은 경우 : input 태그 hide();
if(matchFound) {
$("#inputText").hide();
/* (2) input 값과 select박스 값이 다른 경우
* input 태그 show();
* 마지막 option인 '직접 입력'을 기본값으로 설정
*/
}else {
$("#inputText").show();
selectBox.val(selectBox.find('option:last').val());
}
}
$(function() {
syncInputWithSelect();
// change 이벤트
$("#selectBox").change(function() {
// (1) select 박스의 option에서 '직접 입력'을 선택한 경우 : input 태그 show();
if($("#selectBox").val() == "direct") {
$("#inputText").show();
// (2) select 박스의 option에서 '직접 입력'을 선택하지 않는 경우
}else {
/* select 박스의 option이 비어 있지 않은 경우
* input 태그 hide();
* select 박스의 값으로 input 태그 값에 넣어준다.
*/
$("#inputText").hide();
if($("#selectBox").val() != ""){
$("#inputText").val($("#selectBox").val());
}else {
$("#inputText").val("");
}
}
})
});
728x90
728x90