HTML text field to behave like a password field - javascript

I have a registration form, and i want to use a password field. The problem is, i want it to have a placeholder saying "Password" at the begining so i'm using a text field instead. I need to turn the characters into asterisks or black circles like a password field when the user starts typing.
I've tried changing the "type" attribute to "password" through javascript, so i'm stuck.
Is there a simple way to resolve this with css? or does anyone know of a good javascript(preferably jquery) to hack this?
Thanks

Use a regular password field
Don't abuse the value as a placeholder — it becomes invisible to, among others, screen reader users.
Put the label in a <label>
Position the label behind the input
Restyle the input with JS to change the background
Demo at http://dorward.me.uk/tmp/label-work/example.html

You could use the HTML5 placeholder attribute However, that will not work in all browsers (especially older ones).
<input type="password" name="pwd" placeholder="Enter Password" />

Hover a div or a span tag over your text (password) field, then hide it when the password field takes focus or the div/span is clicked.

Generally, browsers frown at changing the type attribute of input elements via JavaScript. Most workarounds involve cloning the input with the new type, and removing the original.
You could absolutely position the label over the input form, and remove it on focus.
You should consider the implications of not using type="password" - it is the semantically correct option.
Update
Upon reading David Dorward's answer, you should strongly consider his very valid points.

I had a similar problem, where I had the Value of the inputs as my labels, and when you clicked inside one, some Javascript would run, clearing the input. But on the password field, you needed to change the input type from "text" to "password", which works in browsers like Safari or Firefox, but not IE (IE doesn't support the setAttribute function very well). So I was killing myself trying to figure out how best to do this (IE conditionals, etc.)
I found this thread, and I think Quentin had the best idea. Not only because it works and should work in all browsers, but it also provides an actual Label in the code, which, Screenreaders aside, is good practice. Plus, you should always consider those who use screenreaders to some extent.
Here is the basics of the solution:
The HTML:
<label>Enter Password
<input type="password" name="password" class="input" /></label>
The jQuery (note: I am not a jQuery expert. This could probably be written better or more efficient, but for two fields, it works):
$("input[name=password]").focus(function() {
var value = $("input[name=password]").val();
if(value == "") {
$(this).toggleClass("inputBg");
}
});
$("input[name=password]").blur(function() {
var value = $("input[name=password]").val();
if(value == "") {
$(this).toggleClass("inputBg");
}
});
The CSS starts with the Label tag, styled the same as your input class, with a position relative and display block added. Then there are two classes for the input. One that is the correct width, height, etc. positioned absolute, with a higher z-index than the label, BUT WITH NO BACKGROUND. The second class is exactly the same, but WITH THE BACKGROUND.
The jQuery just toggles between the two classes, so you'll see the label under the input, but when you click on the input, the background appears and you can type in text on top of it. Works great, should work in all browsers (although only tested in Safari on Mac and IE/Firefox on Windows). Nice idea Quentin!

Related

Accessibility: show/hide password button in a password input

It's common for password inputs to have a show/hide button but I'm finding little content on the web about any accessibility concerns relevant to them - should I be attaching any kinds of ARIA attributes to the button or password input? Does it make sense for that to be a checkbox or is a button that triggers JS to achieve the effect fine too?
Not sure what I should be looking out for as someone not very steeped in, but wanting to understand accessibility best practices.
Interesting question.
This is perhaps the most relevant bits of litterature I could find on the subject:
A disclosure is a button that controls visibility of a section of content. When the controlled content is hidden, it is often styled as a typical push button with a right-pointing arrow or triangle to hint that activating the button will display additional content. When the content is visible, the arrow or triangle typically points down.
(and)
The element that shows and hides the content has role button.
When the content is visible, the element with role button has aria-expanded set to true. When the content area is hidden, it is set to false.
Optionally, the element with role button has a value specified for aria-controls that refers to the element that contains all the content that is shown or hidden.
See https://www.w3.org/TR/wai-aria-practices-1.1/#disclosure
I'm no usability expert at all but it doesn't seem crazy to see a connection with your use case. So to answer your question here are the ARIA attributes I'd apply, along with some JavaScript.
function toggle_visibility(el) {
const control = el.getAttribute('aria-controls');
const expanded = el.getAttribute('aria-expanded') === 'false';
document.querySelector(`#${control}`).type = expanded ? 'text' : 'password';
el.setAttribute('aria-expanded', String(expanded));
el.textContent = expanded ? 'hide' : 'show';
}
document.querySelector('button').addEventListener('click', ({
target
}) => toggle_visibility(target));
<div>
<label for="password">password</label>
<input type="password" id="password">
<button aria-controls="password" aria-expanded="false">show</button>
</div>
And here's a screencast of the Chrome Dev Tools. Note how in the Accessibility panel we're able to refer to the password control.
As none of the so-far given answers cover the topic completely, I'll try to do it here.
You have at least three possibilities:
A checkbox;
A toggle button;
A button with changing text.
Checkbox
This is the easiest solution.
<label><input id="showPwd" type="checkbox"> Show Password</label>
And then you add some JavaScript to change your password input type from password when the check box is cleared to text when it is checked.
From the user perspective this solution is also the most obvious: both screen reader users and users of other assistive technologies usually easily perceive the state of the check box. Another benefit of this approach is that the status is seen immediately with no need to re-check it with additional commands.
Toggle Button
This involves some ARIA, not much, though.
<button id="showPwd" aria-pressed="false">Show password</button>
This way you will need to change both the button CSS styling and the value of the aria-pressed attribute in your JavaScript (and, of course, change the type of your password input accordingly).
From the user perspective, this approach has both advantages and drawbacks. the main advantage for screen reader users is that when the button is pressed, the user will hear "Show Password button pressed" vs. "Show password button" which would help to spot the status of the button for users with hearing and/or cognitive issues better and faster.
Button with Changing Text
An easy, but kind of oldish solution. You basically have a <button> that says "Show Password", and when the password is revealed, the button would say "Hide Password".
This is the worst solution from the assistive technology user perspective, since a screen reader would not notify its user automagically when the text on the button changes (unless you add some additional black magic like ARIA alerts, but it's not worth it, I'm sure). Typically when the text changes, the user should re-check the status with a command that announces the current line or object.
There is another drawback that spans both button solutions: screen readers usually have a possibility to navigate by element and to spawn lists of elements of the same type. In this case a confusion may occur as the form contains more buttons (at least the submit one). With check boxes the chance of such confusion is much lower, if the form is not crowded with many check boxes.

How to get content length of invalid input?

I have an element:
<input type="number">
When I type in $500, it fails validation, so
console.log("el.value");
//returns ""
This is expected.
Here's the question:
How can I check that there is content?
I'm trying to show/hide placeholder text (no, I can't use the native stuff). It needs to be type="number" because I need to force the mobile number keyboard.
Any thoughts?
Update:
From the responses below I can see that I wasn't clear enough in my question.
1) I need to use JavaScript to tell me whether there is content in the input. (I don't need to extract it, I just need to see whether there is content).
This is tricky, because invalid content (like putting words in a number input field) means the value="" even if there is content typed in.
This is the exact problem I need to solve.
inputEl.validity.valid might work but I can't find any docs on how well it is supported across browsers.
Check if you can do something with that :
html
<input id="my-input" type="number">
js
$(document).ready(function(){
$('#my-input').on('input', function(){
console.log($(this).val());
});
});
At mobile device specially Samsung append value in field do not throw key press event,
you can validate the field with onChange="check(this)"
if (variablename==""){
//no content
}
or
if (variablename.length==0){
//no content
}
If the only reason you need to force the input type to be a number is for the number-pad, why don't you instead make type="text" and pattern="\d*"? This way you can handle and check the input any way you'd like, but still, force the number-pad to show.
<input type="text" pattern="\d*">
This was the one that actually answered it:
How to get the raw value an <input type="number"> field?
Basically you can check input.validity.valid or input.validity.badInput.
Not supported in IE but good support elsewhere.
More details on it here:
https://developer.mozilla.org/en-US/docs/Web/API/ValidityState

How to move placeholder text along with the content of a textbox in HTML?

Suppose this is my textbox:
<input type="text" placeholder="%" />
And a user is supposed to enter a percentage inside, but without the % sign, only the numbers (e.g. 67 in 67%). But I want them to still remember that this is a text box in which you insert a percentage.
So how can I move the placeholder along with the text, make it unable to be deleted, always after the text?
And I do remember seeing it somewhere too, unless I got my facts wrong.
A way to do this would be to have an additional element overlaying the input element and moving the overlayed element as the user types.
But, I think a better UX experience would be to have the element as an add-on appended to the input field, as show in twitter bootstrap. See the "extending form controls" settings:
http://twitter.github.com/bootstrap/base-css.html#forms
You could simulate an input and change the width of the real input using javascript. (The trick is to use some invisible element to catch the needed width)
Exemple using JQuery: http://jsfiddle.net/Vu7hN/
$input.on('change keypress paste focus textInput input', function(){
testWidth.text($input.val());
$input.width(testWidth.width());
});

Enable placeholder in input field such that it empties 'after' user input as opposed to onfocus

I want to use the placeholder attribute for HTML input[type=text] elements such that the placeholder text disappears 'after' the user starts typing as opposed to 'onfocus'. Something like the sign-in page on pivotal tracker: https://www.pivotaltracker.com/signin
So far I've not used the placeholder attribute. Instead I used a 'onkeyup' event on the input field such that it empties the contents of the input field as soon as the user types the first character. To do this I've setup a custom attribute on the input element called 'data-received' which is false by default and is set to true as soon as the user types the first character. (So that it doesnt continue to empty the field). I can do something similar by 'unbinding' the 'keyup' method on the input field.
I m not so happy with this method and I was wondering if there s a better way to do this?
Ok I figured this out. I took some cues from the zendesk site as well. Firstly a placeholder attribute is not used. A label is used along with the input field with position: absolute. Its position to overlap the input field associated with it. Javascript is used to track the onkeyup event and as soon as it sees that the value of the input field is not empty, it simply hides the associated label. If you delete whatever your typed, it shows the label again :)
Check out:
Cross Browser HTML5 Placeholder Text (DEMO)
The placeholder attribute is used (if not using JS) but see above link to do it in a cross browser way.
HTML5 has a placeholder attribute but it may not work in all browsers.
HTML5 Placeholder Input Fields Fixed with jQuery has a fix that makes it work in all browsers.
jQuery plugins that do this
http://webcloud.se/code/jQuery-Placeholder/
http://www.iliadraznin.com/2011/02/jquery-placeholder-plugin/

HTML & Javascript: Using a customized Text Input for Password input

I want to re-invent the password input in HTML.
Okay, here is the work I'd done:
http://www.symplik.com/password.html
(It just a plain html code, nothing really fancy :>)
The "password" is indeed a text input, and I used the onkeyup event to rewrite the input to masking characters.
There're two problems:
(1) backspace or delete cannot be detected
(2) if I type very fast, some characters cannot be captured promptly.
For problem (1). it is partially solved by checking the length of text in the password field and the stored password. Not a very elegant solution anyway.
For problem (2), I'd tried to insert some time delay function in between but still fail. I'd make the field readOnly after every keyUp but it still behaves the same.
Why not use
<input type='password'>
It masks the input for you. No need for javascript.

Categories