Reputation: 1
Could you please help me? This one seems simple but none of my solutions work.
I have a table of pdf links on a page. I want user be able to open them only and only if he is logged in. otherwise an alert message pops up.
If we consider each link is inside a div like below:
<div class="prdc prdc-prodList noAccess">
<a target="_blank" href="/files/test.pdf">Specification</a>
</div>
If user isn't logged in, "noAccess" class is assigned to the link parent otherwise "hasAccess" is assigned to it.
I have this code, but (in case user is logged out) it doesn't work all the times.
$( ".prdc a" ).click(function(e) {
if ( $( this ).parent().hasClass( "noAccess" ) ) {
e.preventDefault();
alert("You should be logged in to have access");
}
});
Does anybody know what is wrong with this code? Or do you know a better solution for this problem?
Thank you in advance
Upvotes: 0
Views: 73
Reputation: 288
do this by first not puting the href
in a
and then when the user has loged in then by using javascript add href
. The following code illustrates this:
<div class="prdc prdc-prodList noAccess">
<a target="_blank" id="link">Specification</a></div>
javascript
var some_function_name = function(){
if( some conditions if the user has loged in or not ){
var a = document.getElementById("link");
a.setAttriblue("href","/files/test.pdf");
}
}
and after the user has loged in the your html will look like this:
<div class="prdc prdc-prodList noAccess">
<a target="_blank" id="link" href="/files/test.pdf">Specification</a></div>
Upvotes: 0
Reputation: 1975
First of all - this is not a good way to do this. This is because some users who know how to handle developer tools might just delete the class noAccess and access your files. Therefore you should either: 1. Not display the links at all if the user is not logged in. 2. Add additional check on the server side for the status of logged in user and prevent download if the user is not logged in.
And answering your question:
This is probably coused by the use of parent()
function. It only gets direct parent of an object, and what you want is closest('.noAccess')
. This function will look all predecesors of a given object which have class noAcess
.
Hope this helps, cheers!
Upvotes: 1