Skip to content

Form 조작

사용자가 select 드롭다운에서 항목을 선택할 때, 선택된 value를 읽어와 콘솔에 출력하는 예제

html
<body>
  <label for="fruitSelect">과일 선택:</label>
  <select id="fruitSelect">
    <option value="apple" selected>사과</option>
    <option value="banana">바나나</option>
    <option value="cherry">체리</option>
    <option value="grape">포도</option>
  </select>
</body>
js
const $fruitSelect = document.getElementById("fruitSelect");

$fruitSelect.addEventListener("change", (event) => {
  console.log(event.target.value);
});

select 요소에서 특정 옵션을 제거하는 예제

html
<body>
  <label for="fruitSelect">과일 선택:</label>
  <select id="fruitSelect">
    <option value="apple" selected>사과</option>
    <option value="banana">바나나</option>
    <option value="cherry">체리</option>
    <option value="grape">포도</option>
  </select>
</body>
js
const $fruitSelect = document.getElementById("fruitSelect");

$fruitSelect.remove(1);

로그인 폼에서 사용자 입력값을 가져와 콘솔에 출력하는 예제

html
<body>
  <label for="userName">이름:</label>
  <input id="userName" type="text" value="바켸빈" />
  <label for="userPassword">비밀번호:</label>
  <input
    id="userPassword"
    type="password"
    placeholder="비밀번호를 입력하세요"
  />
  <button>로그인</button>
</body>
js
const $userName = document.getElementById("userName");
const $userPassword = document.getElementById("userPassword");

const $loginButton = document.querySelector("button");

$loginButton.addEventListener("click", () => {
  console.log($userName.value);
  console.log($userPassword.value);
});

HTML 폼의 입력 필드 값을 JavaScript로 변경

html
<body>
  <label for="userName">이름:</label>
  <input id="userName" type="text" value="바켸빈" />
  <label for="userPassword">비밀번호:</label>
  <input
    id="userPassword"
    type="password"
    placeholder="비밀번호를 입력하세요"
  />
  <button>로그인</button>
</body>
js
const $userName = document.getElementById("userName");
const $userPassword = document.getElementById("userPassword");

$userName.value = "홍길동";

사용자가 비밀번호 입력란에 입력할 때마다, 입력한 값을 실시간으로 출력

html
<body>
  <label for="userName">이름:</label>
  <input id="userName" type="text" value="바켸빈" />
  <label for="userPassword">비밀번호:</label>
  <input
    id="userPassword"
    type="password"
    placeholder="비밀번호를 입력하세요"
  />
  <button>로그인</button>
</body>
js
const $userName = document.getElementById("userName");
const $userPassword = document.getElementById("userPassword");

$userPassword.addEventListener("input", (event) => {
  console.log(event.target.value);
});