가장 쉬운 방법은 모달의 마크 업을 <form>
으로 만드는 것입니다. 이렇게하면 this
과 같이 다양한 이벤트 (예 : hidden.bs.modal
) 핸들러의 .modal()
및 <form>
오브젝트에 모두 액세스 할 수 있습니다.
양식 자체에 액세스 할 수있는 경우 .serializeArray()
jQuery 방법을 사용하거나 아래 예처럼 기본 FormData
클래스를 사용할 수 있습니다.
$('#modal-form').on('hidden.bs.modal', function (event) {
// `this` is the modal window, which is also a `<form>` in our case
// Option 1: using `.serializeArray()` of jQuery
var fieldsAsArray = $(this).serializeArray();
console.log('fieldsAsArray', fieldsAsArray);
// Option 2: using native `FormData` object
var fieldsAsFormData = new FormData(this);
console.log('fieldsAsFormData', fieldsAsFormData);
});
<!-- Note the `<form>` tag -->
<form class="modal fade" id="modal-form" tabindex="-1" role="dialog" aria-labelledby="modal-dialogLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-dialogLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- actual form markup -->
<div class="form-group">
<label for="field1">Example label</label>
<input name="field1" type="text" class="form-control" id="field1" placeholder="Example input">
</div>
<div class="form-group">
<label for="field2">Another label</label>
<input name="field2" type="text" class="form-control" id="field2" placeholder="Another input">
</div>
<!-- /actual form markup -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="save" data-dismiss="modal" type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</form>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal-form">
Open modal form
</button>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script>
참고 : data-dismiss="modal"
뿐만 아니라 속성이 있기 때문에 "변경 사항 저장"버튼 타입 의 비록를 제출 양식은 직접이 방법으로 제출되지 않습니다. 이 속성은 event.preventDefault();
호출로 클릭 이벤트를 캡처합니다. 폼 데이터를 먼저 제출하지 않고 작업하기를 원할 때 시나리오에 맞다고 생각합니다.