[jQuery] select 박스 값변경 및 index 가져오기와 삭제 방법
HTML FORM의 select 박스에서 option의 값을 삭제하거나 추가 변경하는 방법에 대한 테스트 입니다.
보통 예제에서 버전의 명시가 없어 안되는것들이 있는데요.
아래는 테스트한것 그대로 올립니다. jQuery 버전을 확인 하세요. attr 형태는 예전것입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery test </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="select">
<button id="btn_down">btn_down</button>
<button id="btn_up">btn_up</button>
<select id="selectBox" name="selectBox" >
<option value="가나다라1">text-가나다라1</option>
<option value="가나다라2" selected>text-가나다라2</option>
<option value="가나다라3">text-가나다라3</option>
<option value="가나다라4">text-가나다라4</option>
<option value="가나다라5">text-가나다라5</option>
<option value="가나다라6">text-가나다라6</option>
</select>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
// 선택한 값을 가져오기
var selectVal = $( "#selectBox option:selected" ).val();
var selectTxt = $( "#selectBox > option:selected" ).text();
var selectTxt2 = $( "select[name=selectBox] option:selected" ).text();
// 선택된것 index 가져오기
var indexVal = $( "#selectBox option" ).index($( "#selectBox option:selected" ));
var totalVal = $( "#selectBox option" ).length;
console.log('현재 선택된값: ', selectVal, ' 선택된 Text: ', selectTxt, ' 이름으로 확인:', selectTxt2);
console.log('현재 선택된 index값: ', indexVal);
console.log('전체갯수: ', totalVal );
console.log("\n");
// index로 선택하기
var eqVal = indexVal + 1; // 다른 값을 선택
$("#selectBox option:eq("+eqVal+")").prop("selected", "selected");
// 선택된것 index 가져오기
var indexVal = $( "#selectBox option" ).index($( "#selectBox option:selected" ));
var selectVal = $( "#selectBox option:selected" ).val();
console.log('현재 선택된값: ', selectVal);
console.log('현재 선택된 index값: ', indexVal);
console.log("\n");
// 옵션 변경
$("#selectBox option:eq(1)").replaceWith("<option value='2'>Someapples</option>");
// 선택된것 값 변경
$("#selectBox").val("A").prop("selected", true);
// 모두 삭제
// $('#selectBox').empty();
// 추가하기
var option = $("<option value='test22'>test1</option>");
$('#selectBox').append(option);
var testVal = $('#selectBox').append('<option value="test3">test3</option>');
// console.log('testVal: ', testVal);
// console.log("\n");
// 값으로 선택
$('#selectBox').val('가나다라5').prop("selected",true);
// 선택된것 기준으로 이전, 이후 갯수 가져오기
var cnt1 = $("#selectBox option:selected").prevAll().length;
var cnt2 = $("#selectBox option:selected").nextAll().length;
console.log('선택된것 이전 갯수:', cnt1, ' 선택된것 이후 갯수: ', cnt2);
// 다음(after)에 삽입 - 전은 before 를 사용한다
// > 아래처럼 0 으로 하면 맨 앞에 들어가게 된다.
$("#selectBox option:eq(0)").before("<option value='4'>삽입된것</option>");
$("#selectBox option:last").after("<option value='5'>삽입된것5</option>");
$("#selectBox option:last").before("<option value='6'>삽입된것6</option>");
// 값으로 삭제 하기
$('#selectBox').children("[value='test3']").remove();
// index로 삭제 하기
$("#selectBox option:eq(2)").remove();
// 마지막것 삭제 -- 삭제 부분은 테스트 할때는 위에 추가 된것 확인 위해선 주석처리 할 필요 있음
$("#selectBox option:last").remove();
// option 전체 삭제
// $('#selectBox option').remove();
// ----------------------------------------------
// 선택된것 감지 하기
// ----------------------------------------------
$('#selectBox').change(function() {
var value = $(this).val();
console.log('선택된 값:', value);
// select box 전체 색이 아래 설정 된것으로 변경 된다
$(this).css('color', '#070');
});
});
</script>