기본 confirm()으로는 불가능합니다
결론부터 말씀드리면, JavaScript의 내장 confirm() 함수로는 '예(Yes)'와 '아니요(No)' 버튼이 있는 대화 상자를 만들 수 없습니다. 브라우저에서 제공하는 기본 확인 대화 상자에는 오직 '확인(OK)'과 '취소(Cancel)' 버튼만 포함되어 있기 때문입니다.
따라서 '예' 또는 '아니요' 옵션을 가진 대화 상자를 원한다면, HTML과 CSS, 그리고 jQuery를 활용해 사용자 정의(커스텀) 대화 상자를 직접 구현해야 합니다.
커스텀 '예/아니요' 대화 상자 예제
아래는 jQuery를 이용해 '예'와 '아니요' 버튼이 있는 커스텀 확인 대화 상자를 구현한 전체 예제 코드입니다.
전체 소스 코드
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #91FF00;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message"></div>
<button class="yes">Yes</button>
<button class="no">No</button>
</div>
<button onclick = 'functionConfirm("Do you like Football?", function yes() {
alert("Yes")
},
function no() {
alert("no")
});'>submit</button>
</body>
</html>코드 동작 방식
- functionConfirm(msg, myYes, myNo): 표시할 메시지와 함께 '예' 버튼용 콜백(
myYes), '아니요' 버튼용 콜백(myNo)을 매개변수로 전달받습니다. - 메시지 설정:
#confirm영역 안의.message요소에 전달된 메시지를 삽입합니다. - 이벤트 바인딩:
unbind()로 기존 이벤트를 초기화한 뒤, '예'와 '아니요' 버튼에 클릭 이벤트를 새로 연결합니다. 어떤 버튼을 누르든 대화 상자는 먼저 숨겨지고, 이후 해당 버튼에 맞는 콜백 함수가 실행됩니다. - 표시: 마지막으로
show()를 호출해 화면 중앙에 대화 상자를 띄웁니다.
위 예제에서는 '축구를 좋아하시나요?'라는 질문과 함께 대화 상자가 나타나며, 'Yes'를 누르면 "Yes" 알림이, 'No'를 누르면 "no" 알림이 표시됩니다. 배경색, 버튼 스타일 등은 CSS의 #confirm 관련 속성을 수정해 자유롭게 변경할 수 있습니다.
참고: 더 편리한 대안
직접 구현하는 대신 jQuery UI Dialog, SweetAlert2, Bootstrap Modal 같은 검증된 라이브러리를 사용하면 디자인이 완성된 '예/아니요' 대화 상자를 더욱 손쉽게 만들 수 있습니다. 프로젝트 규모와 디자인 요구 사항에 따라 적절한 방법을 선택하시기 바랍니다.