I want to create password toggle function when clicked on the eye icon using Javascript only. I have written code for it but it works only to show the password text and not the other way round. Can someone see the logic error in the code below.
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
function showHide() {
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function() {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShow = 0;
hide();
}
}, false);
}
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" onclick="showHide()" id="eye">
<img src="eye.png" alt="eye"/>
</button>
You are binding click event every time you click a button. You don't want multiple event handlers. Plus you are redefining var pwShown = 0 on every click so you can never revert input state (pwShown stays the same).
Remove onclick attribute and bind click event with addEventListener:
function show() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'text');
}
function hide() {
var p = document.getElementById('pwd');
p.setAttribute('type', 'password');
}
var pwShown = 0;
document.getElementById("eye").addEventListener("click", function () {
if (pwShown == 0) {
pwShown = 1;
show();
} else {
pwShown = 0;
hide();
}
}, false);
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>
The easiest way is using a button with an onclick attribute that toggles the type of the input.
<input type="password" id="password" value="myPassword"/>
<button onclick="if (password.type == 'text') password.type = 'password';
else password.type = 'text';">toggle</button>
You don't need to maintain one extra "pwShown" variable to decide whether to show text or hide it. All you need to do is to examine "type" attribute of "pwd" element as below :
Working Example
JavaScript :
document.getElementById("eye").addEventListener("click", function(e){
var pwd = document.getElementById("pwd");
if(pwd.getAttribute("type")=="password"){
pwd.setAttribute("type","text");
} else {
pwd.setAttribute("type","password");
}
});
HTML :
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
<img src="eye.png" alt="eye"/>
</button>
Follow these steps:
Download the images given below. Make a folder. Add your html file and the images in the same folder. Replace the value of "b.src" in javascript as well as in your html code accordingly.
Images :
function show() {
var a = document.getElementById("pwd");
var b = document.getElementById("EYE");
if (a.type == "password") {
a.type = "text";
b.src = "https://i.stack.imgur.com/waw4z.png";
} else {
a.type = "password";
b.src = "https://i.stack.imgur.com/Oyk1g.png";
}
}
<input type="password" id="pwd">
<button onclick="show()"><img src="https://i.stack.imgur.com/Oyk1g.png" id="EYE"></button>
This is an improvement upon Tunaki's answer. We don't even care to check which state the form field is in already, because this will be entirely determined by the state of the mouse. This allows the password to be only momentarily viewed (only as long as the mouse button is held down over the button.)
<html>
<head>
<title>Visible Password Test</title>
</head>
<body>
Password : <input type="password" name="password" id="password" />
<button type="button" id="eye" title="Did you enter your password correctly?"
onmousedown="password.type='text';"
onmouseup="password.type='password';"
onmouseout="password.type='password';">Peek at Password</button>
</body>
</html>
Based on what you wrote, you are adding the event both in html and in javascript (inside showHide function). May be you can change your js code from what you have, to:
function showHide()
{
var input = document.getElementById("pwd");
if (input.getAttribute("type") === "password") {
show();
} else {
hide();
}
}
The variable "pwShown" is misspelled (as "pwShow") in the else section of your Javascript code. Therefore, pwShown never gets reset to 0.
JQuery solution from my code: (just change the IDs).
$(document).ready(function () {
$("#eye").click(function () {
if ($("#password").attr("type") === "password") {
$("#password").attr("type", "text");
} else {
$("#password").attr("type", "password");
}
});
});
function action() {
var my_pass = document.getElementById("pass");
if (my_pass.type === "password") {
my_pass.type = "text";
} else {
my_pass.type = "password";
}
}
<input type="checkbox" onclick="action()">Show <input type="password" id="pass" value="my-secret">
We can get by using onclick event, let's see example.It is very easy
HTML
<span>
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" onclick="showHide()" id="eye" />
</span>
Javascript
function showHide() {
if (pwd.type == 'text') {
pwd.type = 'password';
}
else {
pwd.type = 'text';
}
}
Simple inline solution:
<input type="password" id="myInput" name="myInput">
<button onclick="myInput.type = (myInput.type=='text') ? 'password' : 'text'; return false;"></button>
In your code everytime when you call showHide() function, pwShown variable is set to 0.
You need to declare pwShown variable as global one.
var pwShown = 0;
function showHide()
{
...
}
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
see also https://www.w3schools.com/howto/howto_js_toggle_password.asp
Dump the eye image and instead use a button showing "Show" or "Hide" according to its state.
Then you just click on the text of the button.
You can stylize the button to be borderless and initially with the same background as its surrounds. Highlight the button by setting .show:hover to either brighten the background of the button or else to brighten the color of the Show/Hide text.
By putting the input and button into the same span, you will have them both inline ( CSS - span{display: inline-block;} ) and vertically align off the same bottom.
Use an ordinary text input just below the span for space to display the validation error alerts. Make sure its tab index is -1 and its background color & border is the same as its surrounding.
.
.
.
<span class="pwSpan">
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" onblur="return checkPassword();"/>
<button type="button" class="show" id="show" value="Show" onclick="showHide()" tabIndex="-1" autocomplete="off" >
</button>
</span>
<input type="text" class="error" name="pwErr" value="" tabIndex="-1" />
.
.
.
function showHide()
{
const pwField = document.getElementById("pwd");
const showHideValue = document.getElementById("show").value;
if(showHideValue.trim() === "Show")
{
showHideValue = "Hide";
pwField.setAttribute('type', 'text');
}
else
{
showHideValue = "Show";
pwField.setAttribute('type', 'password');
}
}
Related
I don't know how to make this work. Does anyone know how to fix this? I have tried multiple different solutions, but they don't work
function submit() {
var user = "test";
if (document.getElementById('#user').input = user) {
//what I need help on
}
}
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
<button class="open-button" onclick="openForm()">Open Form</button>
<div class="form-popup" id="myForm">
<form action="#" class="form-container">
<h1>Login</h1>
<label for="username"><b>username</b></label>
<input type="text" placeholder="username" id="username" name="username" required>
<button type="submit" onclick="submit()" class="btn">Login</button>
// And here
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
First, where is user input element, that you mentioned in JavaScript, there is no input with id user, only one input with id username exist, use that and hashtag is not used for ids in document.getElementById
replace
document.getElementById('#user')
to
document.getElementById('username') // use username and remove the hashtag (#)
Secondly, use value instead of input
document.getElementById('username').value
Returns the value (text) of the input element
Lastly, use == or === operators in statements not = in JavaScript.
Example
if (document.getElementById('username').value === user) { // Replaced = with ===
//what I need help on
}
Full JavaScript Code
function submit() {
var user = "test";
if (document.getElementById('username').value === user) {
//what I need help on
}
}
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
Use this instead
if(document.getElementById('#user').value == user)
I'd suggest you to store the input element in a variable first to dry your code ;)
I see you got the wrong username id, try my code below:
function submit() {
var user = "test";
if (document.getElementById('#username').value == user) {
//what I need help on
}
}
I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn.
I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same.
Thanks!
Id propose something like this
Use a block, which encapsulates the names of variables and functions inside the block scope
Make small functions, which do just one thing
Prefer addEventListener over onclick or onanything
There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
I added a check for validity to the email field with checkValidity method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:
/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
I want to enable my button, when input is filled. I want to do it in pure Javascript.
My code example in HTML:
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name" onkeyup="myFunction()"><br>
<button type="submit" class="button button-dark" id="send">Send message</button>
</form>
And Javascript:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
function myFunction() {
var nameInput = document.getElementById('name').value;
if (!nameInput === "") {
document.getElementById('send').disabled = "false";
}
}
});
I don't know why my button is not changing to enable state after filling something in input. I have tried diffrent ways to do it, but it's still not working.
Please help.
An input element in HTML is enabled only when the disabled attribute is not present.
In your case disabled is always present in your element, it's just that it has a "false" or a "true" value - but this is meaningless according to the specs (http://www.w3schools.com/tags/att_input_disabled.asp)
So you need to remove it altogether:
document.getElementById('send').removeAttribute('disabled')
The problem with your code is that myFunction() isn't available because you defined it in the eventlistener for click.
Complete refactored code answer:
HTML
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name">
<br>
<button type="submit" class="button button-dark" id="send" disabled>Send message</button>
</form>
JS
document.getElementById("name").addEventListener("keyup", function() {
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
document.getElementById('send').removeAttribute("disabled");
} else {
document.getElementById('send').setAttribute("disabled", null);
}
});
Try this one it will work for you
function myFunction() {
document.getElementById('send').disabled = true;
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
alert("Empty");
document.getElementById('send').disabled = false;
}
}
if you want to check the input should not be contain number then we can use isNaN() function, it will return true if number is not number otherwise return false
Your code is almost correct but you have defined myFunction inside a block, so input is not able to find myFunction() inside onkeyup="myFunction()"
so just keep the same outside of DOMContentLoaded event
see working demo
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
});
function myFunction() {
var nameInput = document.getElementById('name').value;
console.log(nameInput);
if (nameInput === "") {
document.getElementById('send').disabled = true;
} else {
document.getElementById('send').disabled = false;
}
}
I am trying to get this simple script to work. Basically, when a user clicks on the Show link, it will display the password in the password text box and hide it when it is clicked again. I have searched for solutions but couldn't find anything for what I need. Here is the code:
JavaScript
function toggle_password(target){
var tag = getElementById(target);
var tag2 = getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.setAttribute('type', 'text');
tag2.innerHTML = 'Hide';
}
else{
tag.setAttribute('type', 'password');
tag2.innerHTML = 'Show';
}
}
HTML
<label for="pwd0">Password:</label>
<input type="password" value="####" name="password" id="pwd0" />
Show
When I click the link, nothing happens. I have tested this without using the if statement too and still did nothing.
you weren't using document on for getElementById
function toggle_password(target){
var d = document;
var tag = d.getElementById(target);
var tag2 = d.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.setAttribute('type', 'text');
tag2.innerHTML = 'Hide';
} else {
tag.setAttribute('type', 'password');
tag2.innerHTML = 'Show';
}
}
your id names are illegal and difficult to work with: pwd'.$x.' you can't have some of those chars.
The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).
also, this method will not work in all browsers, in IE < 9 for instance you can only change .type before the element is attached to the document
try swapping them:
function swapInput(tag, type) {
var el = document.createElement('input');
el.id = tag.id;
el.type = type;
el.name = tag.name;
el.value = tag.value;
tag.parentNode.insertBefore(el, tag);
tag.parentNode.removeChild(tag);
}
function toggle_password(target){
var d = document;
var tag = d.getElementById(target);
var tag2 = d.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
swapInput(tag, 'text');
tag2.innerHTML = 'Hide';
} else {
swapInput(tag, 'password');
tag2.innerHTML = 'Show';
}
}
hope this helps -ck
Here is an example using jQuery (pastebin):
$(document).ready(function() {
$("#showHide").click(function() {
if ($(".password").attr("type") == "password") {
$(".password").attr("type", "text");
} else {
$(".password").attr("type", "password");
}
});
});
#showHide {
width: 15px;
height: 15px;
float: left;
}
#showHideLabel {
float: left;
padding-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" class="password" size="25">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="checkbox" id="showHide" />
<label for="showHide" id="showHideLabel">Show Password</label>
</td>
</tr>
</table>
Sources:
http://www.voidtricks.com/password-show-hide-checkbox-click/
How to align checkboxes and their labels consistently cross-browsers
Because of security reasons you can't change the type of an input element. You have to replace the entire element with a new one.
Its really easy to achieve...I found this blog post which describes the way of doing it with a few lines of code. I think its not a good practice to keep an option like this because passwords must be treated seriously.
here is the code from that page; it uses the same approach as you described. but uses a check-box.and practically i have seen what he points out in oss' like linux. they don't even leave a trace of the password with an asterisk.(but the gui thing does, don't know they really care about pw privacy or they find it difficult to do it in command line ;-) )
var textbox_elem = document.getElementById("password");
if(check_box.checked)
textbox_elem.setAttribute("type", "text");
else
textbox_elem.setAttribute("type", "password");
http://www.voidtricks.com/password-show-hide-checkbox-click/
This is a simple tutorial to show a password in a input box when a checkbox is checked and hide it when the checkbox is unchecked using jQuery.
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#showHide").click(function () {
if ($(".password").attr("type")=="password") {
$(".password").attr("type", "text");
}
else{
$(".password").attr("type", "password");
}
});
});
</script>
<!-- language: lang-html -->
HTML
*
<input type="password" class="password"><br>
<input type="checkbox" id="showHide"> Show?
*
We have a password input field with the class “password” and a checkbox with the id “showHide”
Easy solution for show / hide password using checkboxes, and this is noob level just copy/paste. DONE !!! ;-)
You could use inline script for a simple implementation of show/hide password.
<form>
<input
onmouseover="this.setAttribute('type','text')"
onmouseout="this.setAttribute('type','password')"
placeholder="Hover to show password!"
type="password"
name="password-login"
id="password-login"
>
</form>
If we make a textbox type as "passowrd" then chars are not shown and but when we make a text-box type "text" chars are shown as we type.
Hence the logic is very simple. We can change the type of any HTML element by "setAttribute(type,newvalue)" function of JavaScript.
A complete code example can be seen on below link:
http://www.tutor4web.com/javascript/how-to-show-password-as-text-with-checkbox-using-javascript/
your solution can be
function toggle_pass(){
var pass = document.getElementById('showhide').innerHTML;
if(pass=="show")
{
document.getElementById('pwd0').type = "text";
pass= "Hide";
}
else
{
document.getElementById('pwd0').type = "password";
pass = "Show Password";
}
}
Although the question still has the answer, I am still posting this answer.
function toggle_password () {
var tag = document.getElementById("pwd0");
var tag2 = document.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.type="text";
tag2.innerText = 'Hide';
}
else {
tag.type="password";
tag2.innerText = 'Show';
}
}
<label for="pwd0">Password:</label>
<input type="password" value="####" name="password" id="pwd0" />
Show
I believe this is how you wanted:
function toggle_password(){
var d = document;
var tag = d.getElementById("pwd");
var tag2 = d.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.setAttribute('type', 'text');
tag2.innerHTML = 'Hide';
} else {
tag.setAttribute('type', 'password');
tag2.innerHTML = 'Show';
}
}
#input_field{
margin:25px;
padding:25px;
border:5px solid black;
}
<html>
<head>
</head>
<body>
<div id="input_field">
<label for="pwd">Password:</label>
<input type="password" value="" name="password" id="pwd" />
<a href="#" onclick="toggle_password();"
id="showhide">Show</a>
<div>
</body>
</html>
Don't change input type, change text size. Make it very small for Hide.