Enter password to display content of div - javascript

I'd like to enter the word,PASSWORD and for the content inside HIDDENDIV to display.
Can someone show me where I'm going wrong?
#HIDDENDIV {
display: none;
}
<input type="text" id="password" onkeydown="if (event.keyCode == 13) document.getElementById('button').click()" />
<br/>
<input id="button" type="button" value="Login" onclick="if (document.getElementById('password').value == 'PASSWORD') {
document.getElementById('table').classList.toggle('show'); document.getElementById('passw').style.display='none'; }
else { alert('Invalid Password!'); password.setSelectionRange(0, password.value.length); } " />
<div id="HIDDENDIV">bla</div>

Because you hid the content via an id based CSS selector, adding a "show" CSS class to it later won't override the id rule that you already set. (Read this on how different CSS selectors are more specific than others and thus, more difficult to override.)
Here's a quick example:
#d1 { display:none; } /* Will override most other selectors */
div { display:block; } /* Won't work */
.show { display:block; } /* Won't work */
<p>You aren't going to see the div below this paragraph even though it matches two selectors that indicate that it should be shown and even though those two selectors come after the one that hides it. This is because the way it's being hidden is with an id based selector and tag type and class selectors alone are less specific than an id selector and won't override it.</p>
<div id="d1" class="show">Hello?!</div>
So, first, set the content to be hidden with a CSS class instead of an id based selector, then later, you can just remove that class - no extra "show" class is needed.
Next, in your code you have a div with an id of HIDDENDIV, but your code attempts to get and show an element with an id of table. I'm assuming that this was just a typo when posting this question and that, in reality, you really to have a table to show, but you need to correct that.
Also, you should not be using HTML inline event attributes. This was the way we did event handling 20+ years ago before we had standards and unfortunately, is a technique that is so pervasive that it just won't die the death it deserves. There are a variety of reasons not to use them. Instead, use modern standards and best-practices and do all of your event handling in separated JavaScript.
You also need to add an additional line just before you attempt to select all the text in the password field to give that element the focus, otherwise the select code won't work (see code below for this).
// Get references to the elements you'll be working with
var input = document.getElementById("password");
var div = document.getElementById("HIDDENDIV");
var btn = document.getElementById("button");
// Set up event handlers in JavaScript
button.addEventListener("click", validate);
function validate(){
if (input.value == 'PASSWORD') {
// No need to add a "show" class. Just remove the "hidden" class.
div.classList.remove('hidden');
// Or, add it:
input.classList.add("hidden");
} else {
password.focus(); // <-- If you don't do this first, your select code won't work
password.setSelectionRange(0, password.value.length);
alert('Invalid Password!');
}
}
input.addEventListener("keydown", function(event){
if (event.keyCode === 13){
// No reason to simulate a button click. Just call the code that needs to be run.
validate();
}
});
/* You only need to apply this to elements that should be hidden and
then simply remove this class from hidden elements to show them. */
.hidden { display: none; }
<input type="text" id="password">
<br>
<input id="button" type="button" value="Login">
<div id="HIDDENDIV" class="hidden">bla</div>
NOTES:
Keep in mind that although this code can "work", anyone can defeat
this code quite easily simply by looking at your source code. To
truly protect content from being consumed without the correct
credentials being provided, you need to implement a server-side
solution.
Just like inline scripting should no longer be done, the same can be
said for using XHTML self-terminating tag syntax (i.e. <br />,
<input />). That is also an old syntax that just won't go away.
Here's why you don't need and shouldn't use this syntax.

I modified and cleaned your code to get to this working snippet:
(See my comments in the code)
// Scripts belongs in tag scripts or in separate files, inline scripts shouldn't be that long.
function verify() { // I created the function, which is called onclick on the button
if (document.getElementById('password').value === 'PASSWORD') {
document.getElementById('HIDDENDIV').classList.remove("hidden"); // Using class instead of inline CSS
document.getElementById('credentials').classList.add("hidden"); // Hide the div containing the credentials
} else {
alert('Invalid Password!');
password.setSelectionRange(0, password.value.length);
}
return false;
}
.hidden { /* Changed id selector to a class */
display: none;
}
<div id="credentials">
<!-- Added the parent div to be able to hide both the password, the button and even the <br> tag easily -->
<input type="text" id="password" onkeydown="if (event.keyCode == 13) verify()" />
<br/>
<input id="button" type="button" value="Login" onclick="verify()" />
</div>
<div id="HIDDENDIV" class="hidden">bla</div><!-- Added class -->
Note that this is NOT a way to secure anything.
Just open the code viewer on any browser and you will see the “hidden” div.

changed
document.getElementById('table').classList.toggle('show')
to
document.getElementById('HIDDENDIV').style.display = 'block';
Seems like you have a lot of uneccesary code though
<input type="text" id="password" onkeydown="if (event.keyCode == 13) document.getElementById('button').click()" />
<br/>
<input id="button" type="button" value="Login" onclick="if (document.getElementById('password').value == 'PASSWORD') {
document.getElementById('HIDDENDIV').style.display = 'block'; document.getElementById('passw').style.display='none'; }
else { alert('Invalid Password!'); password.setSelectionRange(0, password.value.length); } " />
<div id="HIDDENDIV">bla</div>

Related

Adding a class to an element to run CSS animation in Javascript

I'm trying to add my CSS animation class to an element when triggered by the js code. JS:
if (document.getElementById("user").value == "test"
&& document.getElementById("pass").value == "test")
{
alert( "Welcome back!" );
}
else {
document.getElementById("fail").className += "animation";
}
The animation won't play when the onclick event listener is triggered. The 'if' part of the statement works correctly but the 'else' part will not run.
CSS:
.animation {
animation: shake 1s;
}
#keyframes shake {
25% { transform: translate(10px)}
50% { transform: translate(-10px)}
75% { transform: translate(10px)}
100% { transform: translate(-10px)}
}
Relevant HTML:
<!--LOGIN-->
<div id="fail">
<p>My Account</p>
<p id="note">Username must be between 6 and 10 characters. <br/>Password must be at least 5 characters contain at least one letter and number.</p>
<form id="login">
<input type="text" placeholder="Username" id="user"/>
<br/>
<input type="password" placeholder="Password" id="pass"/>
<br/>
<input onclick="login()" type="submit" value="Submit">
</form>
</div>
change the submit input attribute type = button.
submit will initiate a request and refresh the page, the animation will not be seen.
U might be putting your script in your login function which submit the form as soon as clicked and reload the page. Try this script...
document.getElementById("login").addEventListener("submit", function (e) {
e.preventDefault();
if (
document.getElementById("user").value == "test" &&
document.getElementById("pass").value == "test"
) {
alert("Welcome back!");
} else {
document.getElementById("fail").className += "animation";
}
});
You need to define load and click events before to add the CSS class.
Try it with the next code and provide feedback please.
<script>
addEventListener("load", eventClick);
function eventClick() {
document.getElementById("user").addEventListener("click", addClass);
};
function addClass() {
var e = document.getElementById("user");
e.classList.add("animation");
};
</script>
ppcoding's solution does work, but in a lot of cases with forms, you do want them to submit—even if you aren't using the built in GET or POST methods for submissions.
Especially for collaboration with other developers, using a <button> with type="submit" is better, so that it's clear that it submits the information.
When doing some kind of custom submission function, you should use preventDefault() on the event:
function login(e) {
e.preventDefault()
// ... continued code
}
Also, it's not recommended to use event listeners in the HTML. It's better to put it in your JavaScript:
<!-- HTML Before -->
<form>
// other inputs
<input onclick="login()" type="submit" value="Submit">
</form>
<!-- HTML After -->
<form id="login">
// other inputs
<button type="submit">Submit</button>
</form>
// JavaScript
const loginForm = document.querySelectorAll('#login')
loginForm.addEventListener('submit', e => {
e.preventDefault()
// ... login
})
I know there was already a solution, but for those that are looking to make their code more professional, this is how you do it.

Javascript - Button visible when has content in a input

I would like that when the user inserts information in a specific input text, another element becomes visible. My question looks study, but I'm new on JavaScript world, and I have tried searching on Google and here but I wasn't able to find anything.
Check out my code:
.hide {
display: none;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput">
Show password
</div>
What I want is that the "Show password" anchor only shows when the password input has content inside.
Super simple option... use the input event handler on the <input> to toggle a class on it. You can then use an adjacent-sibling selector in your CSS to show or hide the <a>.
.hide {
display: none;
}
.has-input + .hide {
display: inline;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput"
oninput="this.classList.toggle('has-input', this.value.trim())">
Show password
</div>
If you're not a fan of inline event handlers, this is the unobtrusive equivalent
document.getElementById('pwInput').addEventListener('input', function(e) {
this.classList.toggle('has-input', this.value.trim())
}, false)
Note, the force option on classList.toggle() doesn't work in IE. If you need to support it, try something like
this.classList[this.value.trim() ? 'add' : 'remove']('has-input')
Just do this in JavaScript:
document.addEventListener("keydown", function() {
if (document.getElementById("pwInput").value != "") {
document.querySelector(".hide").style.display = "inline";
}
else {
document.querySelector(".hide").style.display = "none";
}
});
.hide {
display: none;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput">
Show password
</div>
This will check every keydown if the input has any content, plus it'll work both ways e.g. if the user deletes the password then the anchor will go away.

Hide/Blank out a div until checkbox is selected

I am trying to finalise design of a product page and basket template for my new site but am having trouble putting all the pieces together.
In the html code below the cart/basket is called using <div class="ct-cart"></div> but I need this to either not be visible or blanked out in some way so that a customer has to have ticked the checkbox to agree with the terms and conditions before they can interact with the cart/basket.
I've tried a few scripts I've found online to try and hide it but have been unable to get it to work, even after (hopefully) removing any jQuery conflicts.
Any help would be greatly appreciated.
<p style="text-align:center">
<input type="checkbox" name="tandc" id="tandc" value="true" class="form-control"><label for="tandc"> Please tick box above to confirm you agree with the Terms & Conditions.</label>
</p>
<div class="ct-cart"></div>
Pure JS implementation. (in case you dont really need jquery)
document.getElementById('tandc').onchange = function(){
var cart = document.getElementsByClassName('ct-cart')[0];
if (this.checked) cart.classList.remove('hide');
else cart.classList.add('hide');
}
.hide{
display: none;
}
<p style="text-align:center">
<input type="checkbox" name="tandc" id="tandc" value="true" class="form-control"><label for="tandc"> Please tick box above to confirm you agree with the Terms & Conditions.</label>
</p>
<div class="ct-cart hide">Shown only if checked :)</div>
Something like this:
(Change event on checkbox triggers visibility class on cart div)
$('#tandc').on('change', function(){
if ($(this)[0].checked) {
$('.ct-cart').addClass('ct-cart-visible');
} else {
$('.ct-cart-visible').removeClass('ct-cart-visible');
}
})
/* I would use special classes for showing/hiding, just to give more flexibility on styling, how the cart appears */
.ct-cart {
display: none;
}
.ct-cart-visible {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="text-align:center">
<input type="checkbox" name="tandc" id="tandc" value="true"
class="form-control"><label for="tandc"> Please tick box above to confirm you agree with the Terms & Conditions.</label>
</p>
<div class="ct-cart">CART CONTENTS</div>
When the checkbox changes you need to run a function.
if the checkbox is :checked, show() the .ct-cart. Otherwise hide the cart.
$('#tandc').change(function(){
if($(this).is(":checked")){
$(".ct-cart").show();
}else{
$(".ct-cart").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="text-align:center">
<input type="checkbox" name="tandc" id="tandc" value="true" class="form-control"><label for="tandc"> Please tick box above to confirm you agree with the Terms & Conditions.</label>
</p>
<div class="ct-cart" style="display:none;">
Cart
</div>
One further approach:
function toggle() {
// convert the NodeList returned by document.querySelectorAll()
// into an Array, using Array.from():
Array.from(
// using document.querySelectorAll() to find the elements that
// match the selector returned from changed-element's
// custom data-toggle attribute:
document.querySelectorAll(this.dataset.toggle)
// iterating over the Array of nodes:
).forEach(
// using an Arrow function - which avoids changing the
// 'this' - to toggle the class of 'hidden' depending
// on whether the changed-checbox is currently checked
// or not (applying the class-name if the evaluation is
// true, removing it if false):
el => el.classList.toggle('hidden', !this.checked)
);
}
// creating a custom Event (albeit in this case it's the
// browser's 'change' event):
let changeEvent = new Event('change'),
// caching a reference to the relevant element upon which
// the function should fire:
check = document.getElementById('tandc');
// binding the toggle() function (note the deliberate lack of
// parentheses) as the event-handler for the 'change' event:
check.addEventListener('change', toggle);
// firing the 'change' event on page load,
// in order that the relevant element will be
// shown or hidden appropriately:
check.dispatchEvent(changeEvent);
function toggle() {
Array.from(
document.querySelectorAll(this.dataset.toggle)
).forEach(
el => el.classList.toggle('hidden', !this.checked)
);
}
let changeEvent = new Event('change'),
check = document.getElementById('tandc');
check.addEventListener('change', toggle);
check.dispatchEvent(changeEvent);
.ct-cart {
opacity: 1;
transition: opacity 0.5s linear;
}
.hidden {
opacity: 0.1;
}
<p style="text-align:center">
<input type="checkbox" name="tandc" id="tandc" value="true" class="form-control" data-toggle=".ct-cart" /><label for="tandc"> Please tick box above to confirm you agree with the Terms & Conditions.</label>
</p>
<div class="ct-cart">Cart content</div>
References:
JavaScript:
Array.prototype.forEach().
Array.from().
Arrow functions.
Element.classList API.
Element.datalist.

How to switch between display:none/block of input field using onclick only once?

I would like to change display property of this input (actually of div which contains it) after onclick ("Click here"). This part goes well ... but after clicking again I want it to be hidden again (has display="none" instead of "block" again and so on) and here I have difficulties.
I've tried classList.toggle but ... I' don't want to change classes, I want to change just one property. I know there is also possibility of creating my input field by using Javascript but I presume I'll come to a deadlock again in the same point.
<form role="form">
<p id="mag">Click here!</p>
<div id="switch" class="xxx"style="display:none;" >
<input id="sr"class="offf" autocomplete="off" placeholder="Search" type="text" >
</div>
</form>
document.getElementById("mag").addEventListener("click", function toffi(){
document.getElementById("switch").style.display="block";
console.log(document.getElementById("switch").style.display);
});
http://codepen.io/zeeebra/pen/RgRYxK
Try this:
document.getElementById("mag").addEventListener("click", function toffi(){
var sw = document.getElementById("switch");
if (sw.style.display === "block") {
sw.style.display = "none";
} else {
sw.style.display = "block";
}
console.log(sw.style.display);
});

Dynamic elements with the same class

I'm having some issues regarding dynamically created elements. I'm trying to creating a page for my site which will display a list of users(which has been passed into my view from the controller). For each user i've created a div holder, and inside each div I have two h3 tags displaying both the ID and Name of the user. Each user div also contains a button, which allows a user to be hidden, or shown.
<div class="single-user" id="#user.Hidden.ToString()">
<h3>ID: #user.Id</h3>
<h3>Name: #user.Forename #user.Surname</h3>
<span><input type="submit" class="sub-btn" /></span>
</div>
along with then 'name' and 'id' property I also pass in a 'hidden bool property. This is used to check if a user has been hidden. The problem i'm having is that because the elements have been created dynamically, they all share the same classe's and id's, so i'm unable to check if a user is hidden or not. I looked online and found a possible solutions, however, it's still not working. Here is my javascript code.
<script type="text/javascript">
$('.single-user').on('click', '.sub-btn', function () {
if ($('.single-user').has('#True')) {
console.log("true");
}
else {
console.log("false");
}
});
</script>
Any help would be greatly appreciated.
<div class="single-user" data-visible="#user.Hidden.ToString()">
<h3>ID: #user.Id</h3>
<h3>Name: #user.Forename #user.Surname</h3>
<span><input type="submit" class="sub-btn" /></span>
</div>
<script type="text/javascript">
$(document).on('click', '.sub-btn', function () {
if ($(this).closest('.single-user').attr('data-visible')=="True") {
console.log("true");
}
else {
console.log("false");
}
});
</script>

Categories

Resources