How do I change a string into a password? - javascript

I have:
$('#pass').on('keyup keydown', function() { //the password input
$('#pass-result').text( $(this).val() ); //the input's bullet's, not string value
});
The text value of the password is printed as the input's string. How do I convert it to the password's masqueraded bullet form (•)?

If you're looking for dots to appear in the field when text is typed in it, you should use <input type="password"> instead of <input type="text">:
<input type="password" id="pass" />
which you would get the text from with $("pass").val().
It looks like you want a string of dots instead. To accomplish this, use:
var dots = Array($("pass").val().length + 1).join("•");
To explain:
$("pass").val() gets the text
$("pass").val().length gets the length of that
Array($("pass").val().length + 1) gets a new Array whose length is 1 more than the length of the password text
Array($("pass").val().length + 1).join("•") returns each element of the Array with a dot inserted between each - which is why we needed 1 extra, otherwise we would get a fencepost error.

According to the fact that you only want to parse a string of dots . what you gonna do is (IF YOU USE 2 INPUTS!)
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').val($('#pass-result').val().slice(0,-1) );
}
else {
$('#pass-result').val($('#pass-result').val() + '•');
}
});
didnt test the code though. but it should add a • to the #pass-result on ever key-down in the #pass field. it doesnt remove any on backspace though..
http://jsfiddle.net/7810squo/
if you wanna do it with a <span> you need to use .html()
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').html($('#pass-result').html().slice(0,-1) );
}
else {
$('#pass-result').html($('#pass-result').html() + '•');
}
});
http://jsfiddle.net/u9kdeewd/
EDIT: updated code and provided jsFiddle link

Related

Input type="number" using .includes() is false when looking for decimal

I am trying to get a true/false using .includes(".") on an input type of number.
In my snippet I am always getting that the value is always false in looking to see if the value does NOT have a decimal. Meaning a number like "2" AND "2." are bring back the same result. When the "2." should fall into the ELSE because it does contain a decimal.
If I turn the input type to "text" all works as expected, but when I turn the type into a number, the .includes(".") does not see the input value as having a decimal.
Should be simple, but I have not been able to get past it. I like using the "number" input for built in browser limitations of number only input.
So I have something like this:
var e = document.getElementById("numberBox");
$('#submitBtn').prop('disabled', true);
$(e).on("keyup", function(){
var newValue = this.value;
checkIt(newValue);
});
function checkIt(newValue){
if(newValue >= 1 && !newValue.includes(".")){
//if entering "2." this should not fire, but does if input type is number.
$('#submitBtn').attr('disabled', false);
console.log("TRUE: value does not include a decimal. Value is:" + newValue + ", value type is: " + typeof newValue);
}else{
$('#submitBtn').attr('disabled', true);
console.log("FALSE: value includes a decimal. Value is: " + newValue + ", value type is: " + typeof newValue);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="number" id="numberBox" value=""/>
<input id="submitBtn" type="submit" value="Submit">
The issue that you'll face with input type="number" is that it only allows valid numbers, so if the user were to enter 2., which you and I know is invalid, the control would see that as just 2 which is valid. includes would never pick up the ..
document.querySelector("input").addEventListener("input", function(){
console.log(this.value); // 2 not 2.1
});
Type 2. and watch the console output <input type="number">
To get the behavior you want, you'll need to use a regular text input, and check for bad characters on keydown and validate the input on keyup.
let input = document.querySelector("input");
input.addEventListener("keydown", function(evt){
// prevent non-numeric chars, but allow BACKSPACE and DELETE
let nums = /^\d+|\./g;
let valid = nums.test(evt.key);
// If the input is not valid, backspace, delete or the left/right arrow keys....
if(!valid && evt.code != "Backspace" && evt.code != "Delete" &&
evt.code != "ArrowLeft" && evt.code != "ArrowRight"){
evt.preventDefault();
}
});
input.addEventListener("keyup", function(evt){
let reg = /^(-?\d+\.\d+)$|^(-?\d+)$/gm; // RegExp to test for valid nummber
let valid = reg.test(input.value); // Test the input
input.setCustomValidity(valid ? "" : "Invalid!"); // Set validity
});
input:invalid { border:2px solid red; }
input:valid { border:2px solid green; }
<input>
You could take your input from your DOM, convert it to a string, perform the decimal includes comparison, and convert it back to a float or integer depending on the results of the comparison.
EDIT:
Understood the question clearly.

Validation for not more than one decimal (i.e 2.2 not 2.2.3)

I want to create a script function which will validate if the user input contains more than one decimal i.e 2.434 should be the correct number but if the user tries to input a NUMBER LIKE 2.4.5.6 it will not take the input in the field. It will take only number after a decimal point but not another single decimal point. no 2.2.2. but 2.2222. Will use it in a .net page.
tried different patterns like ^-{0,1}\d+.{0,1}\d*$ but could not get result. added the function i am already using. need to add the decimal part in the given code.
function isNumberKey(evt) {
var first;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
return true;
}
if (charCode == 46 || charCode > 31 && (charCode < 48 ||
charCode > 57))
return false;
return true;
}
text box will take input when 2.22 or 3.455654 but won't take 2.3.34.4. when the user writes something like this the cursor won't change the position or take the input number.
The code provided does not validate the entire string. It just checks that the key pressed is a digit, which does not help much. There are many ways to do what you want:
1- Browser validation using type="number":
You can use an input with type "number"; then the browser will do a validation on its own before the form submits (this also accepts integers though):
<input type="number" name="decimal" />
2- Browser validation using the patternattribute:
A handy property you can set for inputs is the pattern attribute. You can set it to the desired regex, and the browser will make sure the user's input matches the regex before submitting the form.
<input type="text" name="decimal" pattern="^-?\d+\.?\d*$" />
3- Custom validation with Javascript:
This approach definitely gives you more flexibility, and allows you to validate once the user typed the input, instead of validating on form submit.
Assuming you have a text input, you can listen to the onchange event to validate the entire string, after the user has finished typing their input.
Edit: As for the regular expression, you need to escape the dot, so replace (. by \.). Plus, {0, 1} is equivalent to ?, as pointed out by #CodeManiac in the comments.
var input = document.getElementById("decimal-input");
input.onchange = function() {
var text = this.value;
if(!text.match(/^-?\d+\.?\d*$/)) {
this.value = ""; //clear input
console.log("Please enter a valid decimal.");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="decimal-input" placeholder="Enter a decimal..."/>
</form>
in the event target is the reference to the input element. So you are able to obtain the whole string
function isNumberKey(evt) {
s=evt.target.value;
console.log(s);
if (s.length !==0){
arr=s.split(".");
if (arr.length>0){
return false;
}
///... other checks...
}
there might be also a dirty way to check the whole number
try {
x=eval(s*1) ;
} catch (ex){
return false
}
or just do it on the enter key to implement a tiny calculator in your input ;)
Funtion setupField is called with the id of an input field to be initialized with an onkeyup event that will only allow valid input to be entered into the field. The regular expression it uses allows an optional + or - sign. The number itself can be of the format: 123, 123., 123.45, or .45
To allow an initial entry of the +, -, or . characters, the regular expression must also consider these characters to be legal input. When the form is submitted, there is always the possibility that only one of these 3 characters or no characters at all have been entered. It is easy enough to test for a valid decimal number by testing isNan(parseFloat(input)) against the input.
^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$
<!doctype html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8">
<script>
function setupField(field)
{
let re = /^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$/;
field.autocomplete = "off";
field.saveValue = field.value;
field.onkeyup = function() {
var v = field.value;
if (v === '' || re.test(v)) {
field.saveValue = v;
}
else {
field.value = field.saveValue;
}
};
field.onchange = function() {
var v = field.value;
if (isNaN(parseFloat(v)))
console.log('You entered invalid input.');
};
}
function init()
{
setupField(document.getElementById('x'));
}
</script>
<body onload="init();">
<input type="input" id="x" size="10">
</body>
</html>

How to allow only digits to be entered into an input[type="number"] field?

I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Insert '-' every 5 characters as users type [like a product key] [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript)
Insert space after certain character into javascript string
I am trying to write a script that handles product keys like the ones you see on the back of software and games.
I would like so when the user is inputing their key code the '-' are inserted every 5 characters for 5 sets of characters. Ex(ABCDE-FGHIJ-KLMNO-PQRST-UVWXY). So when the user enters ABCDE as soon as the 'E' is enetered a '-' is inserted immeditly after via jQuery or JavaScript.
Thanks In Advance.
Comment if you have any questions or if I was unclear :)
Form:
<form method="post" action="process.php">
<p>Key: <input name="key" id="key" size="40"></p>
<p><input type="submit"></p>
</form>
You can use http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
});
HTML:
<fieldset id="productkey">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
</fieldset>
JavaScript:
$( '#productkey' ).on( 'keyup', 'input', function () {
if ( this.value.length === 5 ) {
$( this ).next().focus();
}
});
Live demo: http://jsfiddle.net/XXLND/3/show/
You can also enhance the code, so that when the last text-box is filled out, a processing mechanism is activated:
$( '#productkey' ).on( 'keyup', 'input', function () {
var $field = $( this );
if ( $field.val().length === 5 ) {
if ( $field.is( ':last-of-type' ) ) {
$field.blur();
processKey();
} else {
$field.next().focus();
}
}
});
Live demo: http://jsfiddle.net/XXLND/4/show/
Simply because I don't like JQuery :)
function insertSpace(string, part, maxParts) {
"use strict";
var buffer = string.split("-"), step, i;
for (i = 0; i < buffer.length; i += 1) {
step = buffer[i];
if (step.length > part) {
buffer[i] = step.substr(0, part);
buffer[i + 1] = step.substr(part) + (buffer[i + 1] || "");
} else if (step.length < part) {
if (i == buffer.length - 1) {
if (!step) {
buffer.pop();
}
} else {
buffer[i + 1] = step + (buffer[i + 1] || "");
buffer.splice(i, 1);
i -= 1;
}
}
}
buffer.length = Math.min(maxParts, buffer.length);
return buffer.join("-");
}
How about using http://digitalbush.com/projects/masked-input-plugin
With that plugin, the following:
jQuery(function($){
$("#key").mask("99999-99999-99999-99999-99999",{placeholder:" "});
});
or, if your key is all letters use:
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
or, if it's alpha/numeric use:
$("#key").mask("*****-*****-*****-*****-*****",{placeholder:" "});
Here's one approach:
// binds to both the 'keyup' and 'paste' events
$('input:text').on('keyup paste', function(e) {
var that = $(this), // caches the $(this)
val = that.val(), // access the value of the current input
key = e.which, // determines which key was pressed
allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing)
// backspace, delete, tab, shift
if ($.inArray(key, allowed) == -1) {
// if the pressed key is *not* an 'allowed' key
if (val.length == 5) {
// focuses the next element
that.next().focus();
}
else if (val.length > 5) {
// truncates the string, if greater than 5 characters
that.val(val.substring(0, 5));
that.next().focus();
}
}
});​
JS Fiddle demo.
The advantage of this approach is that rather than masking or manipulating the entered string, and accounting for multiple edge-cases, you're simply aiding the user by moving the focus at the right point. And, in this case, also allowing the user to refocus the re-edit the previously entered data.
two things:
One the user experience side, I would avoid dynamically adding character in the input field as the user type a code. Depending on the environment you run the risk to interfere with what the user type.
However, the '-' helps user typing the code since this is a reference point for him. So I would suggest to have an input field and to show a pretty version of the code next to it (or make the field invisible and manage the focus of the field yourself).
For the php code, instead of adding a character every 5 characters I would do the opposite and simplify the code by removing all the unnecessary characters.
Something like that
if ( str_replace('-', '', $userInputKey)==str_replace('-', '', $officialKey) {
echo 'Yeah! Valid key!';
}

Categories

Resources