Reputation: 79
When I click a button "click Me" on my page. I want to know that the button is clicked and an alert should pop up saying hi.Here is my code which is not working.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$(this).data('clicked', true);
});
if($('#btn').data('clicked')) {
alert("HI");
}
});
</script>
</head>
<body>
<input id="btn" value="Click Me" type="button"></input>
</body>
</html>
Upvotes: 0
Views: 93
Reputation: 110
You could drop the if statement at all. It's key to put your alert() call in the click Callback function.
$(document).ready(function(){
$("#btn").click(function(){
alert("HI");
});
});
Upvotes: 0
Reputation: 104795
Move the alert
to inside the handler:
$("#btn").click(function(){
$(this).data('clicked', true);
if($(this).data('clicked')) {
alert("HI");
}
});
That if
statement doesn't automatically run (well it does on page load since it's in your DOM ready event) - it has to be within an event.
Upvotes: 2