I'm trying to click on a button (sbtn2
) so that another is triggered (sbtn1
). I try:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<script>
$(function() {
$("#stack").hide();
$("#sbtn2").on("click", function() {
$("#sbtn1").click(function() {
$("#stack").show();
});
});
});
</script>
</head>
<body>
<button id="sbtn1">OK</button>
<button id="sbtn2">See</button>
<p id="stack">
Hi, my name is Stack Overflow!
</p>
</body>
</html>
I would like stack
to appear only when sbtn1
is clicked THROUGH sbtn2
.
That is, I need to press See
so that it clicks OK
and Stack
appears.
CodePudding user response:
Currently, your code makes it so that when you click on button 2, an event handler for button 1 is set up so that you could then click button 1 and see the hidden message.
To make it so that when button 2 is clicked, it performs the same action that button 1 would do, simply set up a handler on button 2 that calls the button 1 click callback function.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<script>
$(function() {
$("#stack").hide();
$("#sbtn1").click(function() {
$("#stack").show();
});
$("#sbtn2").on("click", function() {
$("#sbtn1").click();
});
});
</script>
</head>
<body>
<button id="sbtn1">OK</button>
<button id="sbtn2">See</button>
<p id="stack">
Hi, my name is Stack Overflow!
</p>
</body>
</html>
CodePudding user response:
Try something like this:
Add separate event listeners to both buttons
$(function () {
$("#stack").hide();
$("#sbtn1").on("click", function () {
$("#stack").show();
});
$("#sbtn2").on("click", function () {
$("#sbtn1").click();
});
});