Reputation: 181
I have this simple piece of code, which doesn't work the way I intended it to work. I am trying to create a modal which will either open right away when the page opens or not (if password exists or not). It would ask for the password and only close if the password is correct.
JS :
$(window).load(function(){
$("#error").hide();
$('#passwordModal').modal({
backdrop: 'static'
});
var password = '<?php echo $samples->password;?>';
password = null;
if(password !== null){
console.log(password !== null);
$('#passwordModal').modal('show');
}
$('#passwordModal').on('hide.bs.modal', function(e){
var password = '<?php echo $samples->password;?>';
if($('#psw').val() !== password ) {
$("#error").show();
e.preventDefault();
e.stopImmediatePropagation();
return false;
}
});
});
</script>
HTML :
<div class="container">
<?php echo $samples->password;?>
<!-- Modal -->
<div class="modal fade" id="passwordModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Please enter survey password</h4>
</div>
<div class="modal-body">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
<input type="text" class="form-control" id="psw" placeholder="Enter password">
<div class="alert alert-danger" id="error">
Sorry, wrong password. Please try again to continue!
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Enter</button>
</div>
</div>
</div>
</div>
</div>
Currently it will always open the modal when I load the page and does not check password when I press enter it does not check if the entered password equals the actual password.
EDIT (got it working):
if(password){
console.log(password !== null);
$('#passwordModal').modal('show');
$('#passwordModal').modal({
backdrop: 'static'
});
New EDIT: for best answer check @Shehary comment
Upvotes: 1
Views: 151
Reputation: 9992
As suggested in comments,
Remove
$('#passwordModal').modal({
backdrop: 'static'
});
which fix the issue Currently it will always open the modal when I load the page
For backdorop, include data attributes data-keyboard="false" data-backdrop="static"
in the modal definition itself:
<div class="modal fade" id="passwordModal" role="dialog" data-keyboard="false" data-backdrop="static">
// Modal HTML Markup
</div>
To check if entered password equals the actual password. use change
event on input and if / else condition, if password doesn't match, show error else close modal
$(window).load(function(){
$("#error").hide();
var password = '123123';
//password = null;
if(password == "123123"){
$('#passwordModal').modal('show').on('shown.bs.modal', function(){
var passwordcheck = '123123';
$('#psw').change(function() {
if($(this).val() !== passwordcheck ) {
$("#error").show();
} else {
$('#passwordModal').modal('hide');
}
});
});
}
});
Upvotes: 2