I have broken my problem down to be simple. A guest can post a question and a host can answer them. When the host answers a question, for each question there is a text field with a submit answer button. For the host, there are x amount of buttons on a page at a given time depending on how many questions a guest posts.I am trying to target every submit answer button (that has the same identifier) with a confirm modal. I have managed to target the first button, but for some reason every other button with the same identifier won't target. I also tried to do a for loop through the buttons and essentially wrap a for loop around the sweet alert Javascript to no avail. Here is what I tried. Any help is appreciated.
$(document).ready(function() {
const btnSubmit = document.querySelector('.q_a');
btnSubmit.addEventListener('click', function(e) {
console.log(this.id);
e.preventDefault();
swal({
title: 'Confirm',
text: 'Your question/answer will be publicly visible - it is not a private message. Are you sure you want to proceed?',
buttons: [
'No',
'Yes, I am sure'
]
})
.then((isConfirm) => {
if (isConfirm) {
swal("Confirming...", {
buttons: false,
});
btnSubmit.submit();
} else {
return null;
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<meta name="description" content="This is an example of a meta description.">
<link rel="stylesheet" type="text/css" href="theme.css">
</head>
<body>
<input type="submit" name="commit" value="Submit Answer" class="q_a btn btn-success" id="q_a">
<input type="submit" name="commit" value="Submit Answer" class="q_a btn btn-success" id="q_a">
</body>
</html>
i think u should use document.querySelectorAll('.q_a')
instead of document.querySelector('.q_a')
, and then use for of
to loop each target to bind event。querySelector
just return the first matched dom.
just like:
const btnSubmits = document.querySelectorAll('.q_a');
for(btn of btnSubmits){
btn.addEventListener('click', function(e){
...
})
}