Reputation:
I have 2 buttons. I want to detect if the previous button clicked then on 2nd button click it should display some data otherwise if user is directly clicking on the second button, it should display an alert(please click the previous button first). I have tried to do so but not able to detect whether the 1st button is clicked or not :-(
HTML
<input type="button" id="btn1" value="button1"></input>
<input type="button" id="btn2" value="button2"></input>
JavaScript
$('#btn1').click(function(){
alert('Button 1 Clicked');
});
$('#btn2').click(function(event) {
var inputButton = document.getElementsByTagName('input');
var $target = $(event.target);
if( $target.is(inputButton[1]) ) {
alert("Please click the 1st Button first");
} else{
alert('Button 2 Clicked');
}
});
Upvotes: 1
Views: 3196
Reputation: 747
EDIT: I chose not to use a variable, because there's not really much reason to use one. Avoiding unnecessary scope pollution, and whatnot.
<button id="btn1">First Button</button>
<button id="btn2">Second Button</button
$(document).ready(function() {
$('#btn1').on('click', function() {
alert('Button 1 clicked');
$('#btn2').data('btn1-clicked', true);
});
$('#btn2').on('click', function() {
var el = $(this);
if (el.data('btn1-clicked')) {
alert('Button 2 clicked');
} else {
alert('Please click the 1st button first');
}
})
});
Upvotes: 3
Reputation: 122026
Try to set a flag
var firstButtonClicked;
$('#btn1').click(function(){
firstButtonClicked = true;
alert('Button 1 Clicked');
});
check firstButtonClicked
in second button click.
Upvotes: 0
Reputation: 64496
Try this one define a global variable to track the click of first button
var buttonclicked=false;
$('#btn1').click(function(){
buttonclicked=true;
alert('Button 1 Clicked');
});
$('#btn2').click(function(event) {
if(!buttonclicked){
alert("please click button1 first")
}else{
var inputButton = document.getElementsByTagName('input');
var $target = $(event.target);
if( $target.is(inputButton[1]) ) {
alert("Please click the 1st Button first");
} else{
alert('Button 2 Clicked');
}
}
});
Upvotes: 1
Reputation: 93
I think you can put the second button function in the first one.
$('#btn1').click(function(){
alert('Button 1 Clicked');
$('#btn2').click(function(event) {
var inputButton = document.getElementsByTagName('input');
var $target = $(event.target);
alert('Button 2 Clicked');
}
});
});
You then also won't need the check in the second button.
Upvotes: 0
Reputation: 28845
You could use this, creating a variable to store a true/false related to the first button:
var btn_clicked = false;
$('#btn1').click(function () {
btn_clicked = true;
alert('Button 1 Clicked');
});
$('#btn2').click(function (event) {
var inputButton = document.getElementsByTagName('input');
var $target = $(event.target);
if (!btn_clicked) {
alert("Please click the 1st Button first");
} else {
alert('Button 2 Clicked');
}
});
Upvotes: 2