같은 HTML 파일 내에서 href로 이동할때 동적으로 값 가져오기

왬스터·2025년 2월 13일

같은 HTML 파일 내에서 member_id 값을 동적으로 가져와서 th:onclick에 사용하고 싶어서 이렇게 적었습니다

<input placeholder="아이디를 입력해주세요" type="text" name="member_id" id="member_id" required class="block">
	<div class="absolute bottom-6 right-1">
      <button type="button" th:onclick="|location.href='@{/user/checkId/${member_id}}'|" class="flex">중복 확인</button>
	</div>

작동이 안되는 문제‼️

📌 문제점

  1. member_id는 input 태그의 name 속성에 지정된 값인데, Thymeleaf는 서버에서 렌더링될 때 member_id의 값을 모름.
  2. th:onclick은 서버 사이드에서 변수를 치환하는데, input의 값은 클라이언트에서 입력되므로 Thymeleaf에서 직접 사용할 수 없음.

🎯 해결방법

<button type="button" onclick="checkDuplicateId()" class="flex">중복 확인</button>

onclick을 checkDuplicateId()함수로 바꿔주고

<script>
  function checkDuplicateId() {
  	let memberId = document.getElementById("member_id").value.trim(); //값 가져오기
  	if (memberId === "") {
      alert("아이디를 입력해주세요.");
      return;
    }
  	location.href = `/user/checkId/${memberId}`;
  }
</script>

스크립트를 만들어 주었습니다

성공!

profile
공부를 햄스터하는 남자

0개의 댓글