Reputation: 1329
I have a function that will alert two different things depending on what the id is when the button is clicked. The problem that I'm having is that even though the id changes, when you click the button it still gives the dialogue that it would before the id changed.
$('#loginBtn').on('click', function() {
if ($('.button').has('#loginBtn')) {
$('.button').attr('id', 'logoutBtn');
alert('Logged In!');
} else {
alert('Already Logged In!');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="loginBtn" class="button" href="#">Sign In</a>
Upvotes: 0
Views: 29
Reputation: 207511
if($('.button').has('#loginBtn'))
will always be true even when there are NO matches. The reason, it is not a Boolean, it is an object and objects are truthy.
The check would need to check the length
if($('.button').has('#loginBtn').length)
But it makes no sense why you would not just look up the button by id instead of looking through all of the buttons.
if($('#loginBtn').length)
or just look at the button you clicked
if(this.id==='loginBtn')
Upvotes: 1
Reputation: 388316
this
refers to the button in the click handler
$('#loginBtn').on('click', function () {
if (this.id == 'loginBtn') {
this.id = 'logoutBtn';
alert('Logged In!');
} else {
alert('Already Logged In!');
};
});
.has() is used to filter based on presents of descendant elements matching the passed selector
Upvotes: 1