본문 바로가기

Web

[JAVASCRIPT/JQUERY] SELECT OPTION 동적 추가/삭제

반응형

 

<select id="selectEl">
	<option value="1">1번></option>
	<option value="2">2번></option>
	<option value="3">3번></option>
	<option value="4">4번></option>
</select>

<button id="addButton" onClick="onClickAddButton1()">
추가
</button>
<button id="removeButton" onClick="onClickRemoveButton1()">
삭제
</button>
<button id="addButton" onClick="onClickAddButton2()">
추가
</button>
<button id="removeButton" onClick="onClickRemoveButton2()">
삭제
</button>




<script>
// javascript 이용
  function onClickAddButton1() {
    let selectEl = document.querySelector("#selectEl");
    var objOption = document.createElement("option");
    objOption.text = selectEl.length+1 + "번";
    objOption.value = selectEl.length+1;
    selectEl.options.add(objOption);
  }
  
  function onClickRemoveButton1() {
    let selectEl = document.querySelector("#selectEl");
    selectEl.options.length = 0;
  }
// jquery 이용
  function onClickAddButton2() {
    let selectEl = document.querySelector("select");
    $(selectEl).append("<option value='"+ (selectEl.length+1)+"'>" + (selectEl.length+1) + "번</option>")
  }
  
  function onClickRemoveButton2() {
    let selectEl = document.querySelector("select");
    $(selectEl).empty();
  }
</script>

 

 

 

 

 

 

반응형