이전 자바스크립트 예제 공부하다가 그냥 내가 만들어본 예제이다.

  1. 동물추가 버튼 클릭
  2. 텍스트창에 동물이름 입력
  3. 확인버튼을 누르면 select창에 동물 추가
  4. 중복일 경우 alert창에 알림 + 추가되지 않는다.
셀렉트 박스


jsp06_ex03

jsp06_ex04

<form name="form1">
        <fieldset id="field">
          <legend>셀렉트 박스</legend>
          <label>동물선택</label>
          <hr>
          <select name="sel1" mutiple size="7">
              <option value="1">강아지</option>
              <option value="2">고양이</option>
              <option value="3">거북이</option>
              <option value="4">토끼</option>
              <option value="5">이구아나</option>
          </select>
          <hr>
            <input type="button" value="동물추가" name="btn1">
        </fieldset>
</form>
<script>

  var btn1 = document.form1.btn1;
  var field = document.getElementById("field");
  var sel1 = document.form1.sel1;

  btn1.onclick = function() {

      //동물추가 버튼을 누르면 createElement를 이용해 input 태그를 생성한다.
      //add -> 텍스트창, btn2 -> "확인"버튼
      var add = document.createElement("input");
      var btn2 = document.createElement("input");

      //텍스트창과 확인버튼 사이의 공백을 위한 태그
      var ns = document.createTextNode(" ");

      //setAttribute로 input 태그의 속성을 설정한다.
      add.setAttribute("type", "text");
      add.setAttribute("value", "동물을 입력해주세요.");
      add.setAttribute("onfocus", "this.value=''");
      add.setAttribute("id", "txt1");

      btn2.setAttribute("type", "button");
      btn2.setAttribute("value", "확인");

      //만든 태그들을 하나씩 filed태그 밑에 자식으로 추가시킨다.            
      field.appendChild(add);
      field.appendChild(ns);
      field.appendChild(btn2);


      //btn2 = "확인"버튼
      btn2.onclick = function() {
          //텍스트창 변수
          var txt1 = document.getElementById("txt1");
          //추가할 옵션을 위한 변수
          var op = new Option();

          //추가될 value는 원래 있던 select 길이 + 1
          op.value = sel1.length + 1;
          //추가될 텍스트는 텍스트 창에 입력한 값
          op.text = txt1.value;

          var flag = true;

          //중복값 제어
          for (var i=0; i<sel1.length; i++) {
              if (sel1[i].text == op.text) {
                  flag = false;
                  alert(op.text + "은(는) 중복된 동물입니다.");
                  txt1.onfocus();
                  break;
                }
          }

              if(flag) {
                  sel1.add(op);
                  txt1.onfocus();
              }

          }

      }//btn1.onclick

</script>

getElementById

  • id로 태그 얻기
  • DOM
  • document.getElementById(“id명”);

createElement

  • 태그 생성
  • document.createElement(“태그명”);

createTextNode

  • 텍스트 넣기(PCDATA)
  • document.createTextNode(“텍스트”);

onfocus();

  • 해당 텍스트창에 포커스 맞추기

<input type='text' value="클릭!" onfocus="this.value=''">
  • 포커스 시 텍스트 창에 있던 값은 없어진다.
💗 개발 공부하는 블로그입니다. 틀리거나 문제될게 있다면 코멘트 부탁드립니다. 👉👈