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.
Related
I have a simple code in order to hide objects inside a div until a button is pressed.
The code works, but after execute the alert, the code roll back.
I understand there are several options to do the same, but same behavior occurs for others I have attempt (such as https://www.w3schools.com/jsref/prop_style_visibility.asp).
So I have attempt the removeAttribute style because it's easier to watch on Console.
I have attempt to put the script before the form, and after form, but same behavior occurs.
I have add some snapshots from Console in order to demonstrate it, please see below.
I am not sure what am I doing wrong. Tested on Chrome (89.0.4389.114) and Edge (89.0.774.75).
Any help is highly appreciated!
Thank you in advance.
PS. It is running inside a php code (using echo) due it has conditional values.
**PS. It works fine outside a form**
<body>
<form ...
(...)
<div class="field" id="pwdDIV" style="visibility: hidden">
..somocode..
</div>
<button class="button" onclick="showPwd()">Show Password</button>
</form>
<script>
function showPwd() {
var z = document.getElementById('pwdDIV');
alert("Get Style: "+z.style.visibility);
if (z.style.visibility === 'hidden') {
z.removeAttribute("style");
alert("Change to Style: "+"visible");
} else {
(...)
}
}
</script>
</body>
Before Press Show Password button
After press Show Password button - executing alert parameter
After execute Javascript code
Outside form sample (works fine outside forms)
<html>
<head>
<script type="text/javascript">
function showPwd() {
var z = document.getElementById('pwdDIV');
if (z.style.visibility === 'hidden') {
z.removeAttribute("style");
} else {
z.setAttribute("style", "visibility: hidden");
}
}
</script>
</head>
<body>
<button onclick="showPwd()">Show Password</button>
<div id="pwdDIV" style="visibility: hidden">
<input type="password" id="pwd1" name="pwd1">
</div>
</body>
</html>
I have to build a dialog in my entry site. The problem is, it appears every time and I can't close it (click on the button just refreshes the site, with the dialog appearing again). I also thing that I know the reason, but I'm able to fix it.
This is my dialog
<p:dialog id="ac-wrapper" widgetVar="test" style='display: none; background:white;' modal="true"
resizable="false" closeOnEscape="true" closable="true" visible="true">
<div id="popup">
<h2>Some Content</h2>
<input type="submit" name="submit" value="Submit"
onclick="DialogBox('hide')" />
</div>
</p:dialog>
Here is the javascript that should handle this:
<script type="text/javascript">
$ = jQuery;
function DialogBox(hideOrshow) {
if (hideOrshow == 'hide') {
localStorage.setItem("isShown",1);
document.getElementById('ac-wrapper').style.display = "none";
document.getElementById('ac-wrapper').visible="false";
$("#ac-wrapper").close();
}
else if(localStorage.getItem("isShown") == null) {
document.getElementById('ac-wrapper').removeAttribute('style');
localStorage.setItem("isShown",1);
}
}
window.onload = function () {
setTimeout(function () {
if(localStorage.getItem("isShown") != 1 ){
DialogBox('show');
}
else if(localStorage.getItem("isShown")){
$("#ac-wrapper").remove();
}}, 1000);
}
</script>
By rendering the site, the dialog always appeares because the visible attribute is set on "true". I guess the order is incorrect. It should frist check the local storage and then render the elements, I'm not getting it to work correctly. I also looked for answeres here with similar problems, but nothing helped.
The issue is this
<input type="submit" name="submit" value="Submit"
onclick="DialogBox('hide')" />
because its an input type submit, its defaulting to the form behavior... which is to redirect to the same url using GET. Change the type and value to "button" and "close" and your problem will be resolved
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>
i need to display image when form is processing
And this following code works problem is when i press submit image is displayed but if there are some error in form filed the form will not process but images is displayed
How do i make images display when user press submit button the image should appear only when form is processing
CODE
<input onclick="showImg()" class="btn btn-success" type="submit" name="submit" value="Search"/>
<img alt="" src="ajax-loader.gif" id="progress_img" style="visibility:hidden;">
<script language="javascript" type="text/javascript">
function showImg()
{
if (document.getElementById) {
(document.getElementById("progress_img")).style.visibility = "visible";
}
}
</script>
Well I have created a small demo. Check it out.
var progressImg = document.getElementById('progress_img');
var myForm = document.getElementById('myForm');
myForm.onsubmit = onFormSubmit;
function onFormSubmit() {
var error = false;
// Check for errors
if (error) {
// Show error messages
} else {
// Display the image
progressImg.style.display = 'block';
// Do your AJAX call
// and hide the image when AJAX is completed
}
// This is to prevent the form from submitting
return false;
}
#progress_img {
width: 20px;
height: 20px;
display: none;
background: #aaa;
}
<form id="myForm" action="#">
<input class="btn btn-success" type="submit" name="submit" value="Search" />
<img id="progress_img" src="ajax-loader.gif" alt="">
</form>
If anything is not clear for you, feel free to ask me.
I don't think I fully undestood what you are trying to do, but you could validate all the things you need using javascript.
The best way to achieve what you are willing is to change the button type to "button", not "submit" and then on the "onClick" "showImg()" function, replace it for the validations, then show the image, and then use the javascript submit function. I know it's easy with
document.getElementById("myForm").submit();
Ok Guys I need help in this case and please help if you can :(
I have following div created with text-type input
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input"/>
</form>
</div>
</div>
I have also created above .footer .mainBody
<div class="mainBody">
<script src="Scripts/main.js">
var h = document.getElementById('input').value;
document.write(h);
</script>
</div>
And I have included Javascript in it
I want to work it this way: when I input text in input tag to appear in .mainBody div.
And also do I need button to submit input or it can be done with key press for Ex. "Enter"?
Guys onkeyup="writeThis()" isn't working it just reloads page :(
To execute some events on keyevents, you need to write the onkeyup or onkeydown or any other key function in the element. And in that attribute you can add the function's name which would respond to the event. I will write my function's name as writethis() which will write the value to the div.
You then need to use this:
<input type="text" id="input" onkeyup="writethis()" />
And the function would be:
function writethis() { // the function
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h; // the input
}
This way, you will get the input written on a keypress!
You can also try and use some keyevents such as:
if(event.keyCode == 13) { // enter key event
/* key code for enter is 13
* do what so ever you want */
}
Ok, try this as your JS script content in html head section:
function writeOnBody() {
var inputText = document.getElementById('input').value;
var mainBodyEl = document.getElementById('mainBody');
mainBodyEl.innerHTML = inputText;
}
your HTML code:
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input" onkeyup="writeOnBody()" />
</form>
</div>
</div>
<div id='mainBody' class="mainBody"></div>
I hope it helps. JSFiddle sample: http://jsfiddle.net/amontellano/JAF89/
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h;
avoid using getElementsByClassName instead give you div a id and use getElementById..
rest is in my opinion the best solution..
and yes you can also you a button also all you have to do is call you function on onclick event like this
<button onclick="functionZ()">click me</button>
and define that functionZ in your java script
What we are doing here is..
Adding a button and a click event upon it..such that when that button will be clicked it will call a function for us..
Make sure to add your scripts in lasts part of your page as page loads from top to bottom so its good practice to add scripts just near to end of body