JS - Select input 다루기

신혜원·2023년 5월 23일
0

JavaScript

목록 보기
28/39
post-thumbnail

select 가 들어간 폼

<form class="container my-5 form-group">
    <p>상품선택</p>
    <select class="form-select mt-2">
      <option>모자</option>
      <option>셔츠</option>
    </select>
</form>


<select>은 사용자가 고를 수 있는 선택지를 드랍다운 메뉴로 제공하는 <input> 이다
선택지는 <option>으로 넣으면 된다

-<select> 태그도 선택 시 input, change 이벤트가 발생한다
input, change 이벤트 기록은 여기~!
-<select> 태그도 .value로 유저가 입력한 값을 가져올 수 있다

셔츠고르면 밑에 <select> 더 보여주기


⭐ UI 만드는 방법!! ⭐
html css를 미리 디자인해놓고 원할 때 보여주면 된다!!!!

<form class="container my-5 form-group">
    <p>상품선택</p>
    <select class="form-select mt-2">
      <option>모자</option>
      <option>셔츠</option>
    </select>
    <select class="form-select mt-2 form-hide">
      <option>95</option>
      <option>100</option>
    </select>
</form>

미리 <select>를 추가하고 form-hide 클래스에 display: none; 을 주면
form-hide를 붙였다가 뗐다 하기
"유저가 셔츠선택하면 form-hide 제거해주세요~" 라고 코드짜기

<script>
  if (유저가 선택한거 = 셔츠 일때) {
    $('.form-select').eq(1).removeClass('form-hide');
  }
</script>
<script>
  var value = $('.form-select').eq(0).val();
  if (value == '셔츠') {
    $('.form-select').eq(1).removeClass('form-hide');
  }
</script>

jquery이기 때문에 .val() 을 쓰면 유저가 <select>에서 뭘 선택했는지 알 수 있다~

<script>
  let value = $('.form-select').eq(0).val();
  if (value == '셔츠') {
    $('.form-select').eq(1).removeClass('form-hide');
  }
</script>

-> 작동 안한당,, 왜?

<script>안에 대충 적은 코드는 처음 페이지 로드 시 1회만 실행됨

위에 적은 코드는 페이지 로드 시 1회만 실행되고 다시 실행되지 않는다
그렇다면 <select>를 조작할 때마다 실행되게 해야한다
-> 이벤트리스너 부착하기

<script>
  $('.form-select').eq(0).on('input', function(){

    let value = $('.form-select').eq(0).val();
    if (value == '셔츠') {
      $('.form-select').eq(1).removeClass('form-hide');
    }

  });
</script>

<input>이나 <select>를 조작할 때 input 이벤트가 발생하기 때문에 이벤트리스너 부착하기!

(응용)

: '모자' 를 선택했을 때 <select>를 다시 숨기는 기능 만들기

<script>
 $(".form-select").eq(0).on("input", function () {
  let val = $(".form-select").eq(0).val();
  if (val == "모자") {
   $(".form-select").eq(1).addClass("form-hide");
   }
 });
</script>

0개의 댓글