[Travel] Join 폼 Email 입력(select option), 템플릿 리터럴
Join 폼 Email 입력(select option), 템플릿 리터럴
Sep 29, 2024
도메인 선택 시 화면

직접 입력 선택 시 화면(칸이 비워진다.)

1. 삼항 연산자 사용 전 자바스크립트
// email 입력
function toggleCustomEmail(selectElement) {
const customEmailDomain = document.getElementById('custom_email_domain');
const emailDomainSelect = document.getElementById('email_domain'); // 도메인 선택 select 요소
if (selectElement.value === 'custom') {
customEmailDomain.style.display = 'block'; // 직접 입력 필드 보이기
customEmailDomain.value = ''; // 직접 입력 초기화
emailDomainSelect.style.display = 'none'; // 도메인 선택 select 숨기기
} else {
customEmailDomain.style.display = 'none'; // 직접 입력 필드 숨기기
}
}
function getFullEmail() {
const emailField = document.getElementById('email').value; // 아이디 부분
const emailDomainSelect = document.getElementById('email_domain').value; // 도메인 선택 값
const customEmailDomain = document.getElementById('custom_email_domain').value; // 직접 입력 도메인
let domain;
// 직접 입력한 도메인이 있으면 그 도메인을 사용하고, 그렇지 않으면 선택된 도메인 사용
if (emailDomainSelect === 'custom') {
domain = customEmailDomain;
} else {
domain = emailDomainSelect;
}
// 이메일 필드에 완성된 이메일을 업데이트
const fullEmail = emailField + domain;
console.log('완성된 이메일: ' + fullEmail);
// 최종 이메일 값을 반환
return fullEmail;
}
// 폼 제출 시 이메일 값을 업데이트하고 제출하는 로직 추가
document.getElementById('signup-form').addEventListener('submit', function(event) {
const fullEmail = getFullEmail(); // 이메일 값 생성
console.log('서버로 전송할 이메일: ' + fullEmail);
document.getElementById('email').value = fullEmail; // 폼 제출 전에 이메일 필드에 최종 값 설정
});
//이 코드는 email필드에 입력된 이메일 아이디와 select로 선택된 도메인 또는 직접 입력된 도메인을 합쳐서, 최종적인 이메일 주소를 서버로 전송하기 위한 것입니다.
2. 삼항 연산자로 사용 후 코드
// email 입력 처리 함수
function toggleCustomEmail(selectElement) {
const customEmailDomain = document.getElementById('custom_email_domain');
const emailDomainSelect = document.getElementById('email_domain'); // 도메인 선택 select 요소
// 여기는 삼항 연사자를 안 쓴 이유는 직접입력 필드 선택시
// select 옵션을 안 보이게 하기 위해서 삼항연사자를 쓰지 않았다.!
// '직접 입력'을 선택했을 때만 필드 보이기, 그 외에는 숨기기
if (selectElement.value === 'custom') {
customEmailDomain.style.display = 'block'; // 직접 입력 필드 보이기
customEmailDomain.value = ''; // 직접 입력 초기화
emailDomainSelect.style.display = 'none'; // 도메인 선택 select 숨기기
} else {
customEmailDomain.style.display = 'none'; // 직접 입력 필드 숨기기
}
}
// 이메일 값을 생성하는 함수
function getFullEmail() {
const emailField = document.getElementById('email').value; // 아이디 부분
const emailDomainSelect = document.getElementById('email_domain').value; // 도메인 선택 값
const customEmailDomain = document.getElementById('custom_email_domain').value; // 직접 입력 도메인
// 삼항 연산자로 도메인 선택 및 빈 값 처리
const domain = emailDomainSelect === 'custom' ? customEmailDomain : emailDomainSelect;
// 템플릿 리터럴을 사용하여 이메일 완성
const fullEmail = `${emailField}${domain}`;
console.log('완성된 이메일: ' + fullEmail);
return fullEmail; // 최종 이메일 반환
}
// 폼 제출 시 이메일 값을 업데이트하고 제출하는 로직
document.getElementById('signup-form').addEventListener('submit', function(event) {
const fullEmail = getFullEmail(); // 이메일 값 생성
console.log('서버로 전송할 이메일: ' + fullEmail);
document.getElementById('email').value = fullEmail; // 폼 제출 전에 이메일 필드에 최종 값 설정
});여기는 삼항 연사자를 안 쓴 이유는 직접입력 필드 선택시 select 옵션을 안 보이게 하기 위해서 삼항연사자를 쓰지 않았다.!
// '직접 입력'을 선택했을 때만 필드 보이기, 그 외에는 숨기기
if (selectElement.value === 'custom') {
customEmailDomain.style.display = 'block'; // 직접 입력 필드 보이기
customEmailDomain.value = ''; // 직접 입력 초기화
emailDomainSelect.style.display = 'none'; // 도메인 선택 select 숨기기
} else {
customEmailDomain.style.display = 'none'; // 직접 입력 필드 숨기기
}
}
3. 템플릿 리터널
삼항 연사자로 바꾸기 작업을 하다가 템플릿 리터럴을 대해서 조금 더 알아 보았습니다.
템플릿 리터럴(Template Literal)은 문자열을 보다 간결하고 직관적으로 작성할 수 있게 도와주는 ES6(ECMAScript 2015) 문법입니다. 기존의 문자열 연결 방식보다 더 가독성이 좋고, 문자열 안에서 변수를 쉽게 삽입할 수 있다는 장점이 있습니다.
템플릿 리터럴은 백틱(backticks)(
`)으로 감싸서 사용하며, 변수를 삽입할 때는 **${}**를 사용합니다.기존 방식 (문자열 연결)
기존에는 문자열과 변수를 결합할 때
+ 연산자를 사용했습니다.
let name = 'John';
let age = 30;
let message = 'My name is ' + name + ' and I am ' + age + ' years old.';
console.log(message);템플릿 리터럴 방식
템플릿 리터럴을 사용하면 문자열을 **백틱(
`)**으로 감싸고, 변수는 ${} 안에 넣어주면 됩니다. 훨씬 더 직관적이죠.
let name = 'John';
let age = 30;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);주요 특징
- 변수 삽입:
${}안에 변수를 넣어서 쉽게 삽입할 수 있습니다.
- 멀티라인 문자열: 템플릿 리터럴을 사용하면 여러 줄의 문자열을 쉽게 작성할 수 있습니다.
멀티라인 문자열
기존 방식에서는 여러 줄을 작성할 때
\n을 사용해야 했습니다.
let multiline = 'This is the first line\nThis is the second line';템플릿 리터럴을 사용하면 엔터를 직접 입력해도 멀티라인 문자열이 작성됩니다.
let multiline = `This is the first line
This is the second line`;결론
템플릿 리터럴은 코드 작성이 간결하고 가독성이 좋아지는 강력한 도구입니다. 문자열 안에서 변수와 표현식을 쉽게 사용할 수 있어 다양한 상황에서 유용합니다.
Share article