Я не хочу, чтобы модальное окно закрывалось при нажатии кнопки сброса. Он должен просто сбросить внутреннюю форму. Но мой код закрывает модальный.
<!doctype html>
<html lang = "en">
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" integrity = "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin = "anonymous">
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity = "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin = "anonymous"></script>
</head>
<body>
<div class = "modal fade" id = "messagemodal" tabindex = "-1">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Modal title</h5>
<button type = "button" class = "btn-close" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Modal body text goes here.
<form action = "/action_page.php">
<label for = "fname">First name:</label><br>
<input type = "text" id = "fname" name = "fname" value = "John"><br>
<label for = "lname">Last name:</label><br>
<input type = "text" id = "lname" name = "lname" value = "Doe"><br>
</form>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-secondary" data-bs-dismiss = "modal" onclick = "$('form').trigger('reset');return false;">Reset</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
var modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
</script>
</body>
Удалите data-bs-dismiss = "modal"
из кнопки сброса и добавьте ее к кнопке закрытия. Примечание: если вы хотите, чтобы модальное окно оставалось открытым, когда пользователь щелкает за его пределами, вы можете добавить этот data-bs-keyboard = "false" data-bs-backdrop = "static"
в родительский div с id="messagemodal"
Хотя первым шагом является удаление атрибута data-bs-dismiss
и значения, это само по себе не сбрасывает <form>
, хотя, очевидно, предотвращает закрытие модального окна:
const modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" integrity = "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin = "anonymous">
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity = "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin = "anonymous"></script>
<div class = "modal fade" id = "messagemodal" tabindex = "-1">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Modal title</h5>
<button type = "button" class = "btn-close" data-bs-dismiss = "modal" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Modal body text goes here.</p>
<form action = "/action_page.php">
<label for = "fname">First name:</label><br>
<input type = "text" id = "fname" name = "fname" value = "John"><br>
<label for = "lname">Last name:</label><br>
<input type = "text" id = "lname" name = "lname" value = "Doe"><br>
</form>
</div>
<div class = "modal-footer">
<button type = "reset" class = "btn btn-secondary">Reset</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Вместо этого вы также должны удалить:
onclick = "$('form').trigger('reset');return false;"
Потому что использование onclick
является устаревшей практикой, и вы используете jQuery, хотя даже нативный JavaScript предлагает лучший ненавязчивый подход, чем встроенные обработчики событий.
const modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
// I'd prefer a better selector, but I'm working with what you
// have, so here we retrieve the 'reset' button and use the
// on() method to bind the anonymous function as the
// event-handler for the 'click' event:
$('button.btn.btn-secondary').on('click', function(e){
// here we find the closest '.modal' element:
let modal = $(this).closest('.modal'),
// from the .modal we find the <form> element:
form = modal.find('form');
// and then trigger the reset() function:
form.trigger('reset');
})
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" integrity = "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin = "anonymous">
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity = "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin = "anonymous"></script>
<div class = "modal fade" id = "messagemodal" tabindex = "-1">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Modal title</h5>
<button type = "button" class = "btn-close" data-bs-dismiss = "modal" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Modal body text goes here.</p>
<form action = "/action_page.php">
<label for = "fname">First name:</label><br>
<input type = "text" id = "fname" name = "fname" value = "John"><br>
<label for = "lname">Last name:</label><br>
<input type = "text" id = "lname" name = "lname" value = "Doe"><br>
</form>
</div>
<div class = "modal-footer">
<button type = "reset" class = "btn btn-secondary">Reset</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Как уже отмечалось, это также легко сделать в собственном JavaScript (хотя, по общему признанию, вы, вероятно, используете jQuery по другим причинам):
const modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
// caching the resetButton:
let resetButton = document.querySelector('button.btn.btn-secondary');
// binding the anonymous function of EventTarget.addEventListener() as
// the event-handler for the 'click' event:
resetButton.addEventListener('click', function(evt) {
// caching a reference to the clicked element:
let button = evt.currentTarget,
// finding the closest ancestor '.modal' element:
modal = button.closest('.modal'),
// finding the <form> element within the .modal element:
form = modal.querySelector('form');
// calling the reset() function on the <form>:
form.reset();
})
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" integrity = "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin = "anonymous">
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity = "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin = "anonymous"></script>
<div class = "modal fade" id = "messagemodal" tabindex = "-1">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Modal title</h5>
<button type = "button" class = "btn-close" data-bs-dismiss = "modal" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Modal body text goes here.</p>
<form action = "/action_page.php">
<label for = "fname">First name:</label><br>
<input type = "text" id = "fname" name = "fname" value = "John"><br>
<label for = "lname">Last name:</label><br>
<input type = "text" id = "lname" name = "lname" value = "Doe"><br>
</form>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-secondary">Reset</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Кроме того, хотя это оказывает пагубное влияние на ваш макет/презентацию, важно помнить, что JavaScript не требуется для функции сброса, если кнопка сброса (<button type = "reset">
) находится внутри самого <form>
, как показано ниже:
const modal = new bootstrap.Modal(document.getElementById('messagemodal'), {
keyboard: false
});
modal.show();
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel = "stylesheet" integrity = "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin = "anonymous">
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity = "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin = "anonymous"></script>
<div class = "modal fade" id = "messagemodal" tabindex = "-1">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Modal title</h5>
<button type = "button" class = "btn-close" data-bs-dismiss = "modal" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Modal body text goes here.</p>
<form action = "/action_page.php">
<label for = "fname">First name:</label><br>
<input type = "text" id = "fname" name = "fname" value = "John"><br>
<label for = "lname">Last name:</label><br>
<input type = "text" id = "lname" name = "lname" value = "Doe"><br>
<div class = "modal-footer">
<button type = "reset" class = "btn btn-secondary">Reset</button>
<button type = "button" class = "btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
Использованная литература:
Element.closest()
.Element.querySelector()
.Event
.EventTarget.addEventListener()
.