Hide a part of input as password - javascript

I have a <input type="text"> in which i consider the pattern A B C
Example value:
Hello guys this is a sample
Hello is A
guys is B
this is a sample is C
I would like to transform C to be like if it was a type="password" only for C.
But I must use only one input.
So, after there are 2 spaces, next part become hidden.
Is it possible ?
I can use css/js.

You need to create a code to do it. You need to list 'keydown' and 'keyup' events.
Maybe this example can be near that you want.
https://codesandbox.io/s/hide-part-input-q5yzd
In HTML
<body>
<h1>Example</h1>
<label>Type here the word</label><input id="input" type="text" style="margin-left: 10px; width: 300px" />
<br />
<label>Without transform</label>
<input id="input2" type="text" disabled style="margin-left: 10px; width: 300px" />
<script src="src/index.js"></script>
</p>
</body>
And in javascript:
import './styles.css';
let inputTextOriginal = [];
let inputTextModified = [];
let numSpaces = 0;
const node = document.getElementById('input');
console.log('node', node);
node.addEventListener('keydown', function(event) {
const keycode = event.keyCode;
console.log('keycode', keycode);
if (
(keycode > 47 && keycode < 58) || // number keys
keycode === 32 || // spacebar
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) // numpad keys
) {
inputTextOriginal.push(event.key);
if (numSpaces >= 2) {
inputTextModified.push('*');
} else {
inputTextModified.push(event.key);
}
if (keycode === 32) {
numSpaces++;
}
}
if (keycode === 8) {
inputTextModified.pop();
let deleteKey = inputTextOriginal.pop();
if (deleteKey === ' ') {
numSpaces--;
}
}
});
node.addEventListener('keyup', function(event) {
node.value = inputTextModified.join('');
document.getElementById('input2').value = inputTextOriginal.join('');
});

This can't be done using a single input field. One input field can have one type. You can have a hacky solution where you can put two inputs wrapped inside a div. So that, it appears as one input only.
Hope this helps

Related

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

Next input element is not selected when span is detected

I have a set of input elements within 2 span block. I need to automatically select next input element by using onKeup(). This works fine until span tag is found. After that it is not detecting.
In the following code next input element is detected until 3rd input box after that it is not detected.
Can any one help with this?
http://jsfiddle.net/et3escuh/8/
<span>
<input id="opnamenummer6" class="form-control" type="text" name="opnamenummer6" value="" maxlength="1">
<input id="opnamenummer7" class="form-control" type="text" name="opnamenummer7" value="" maxlength="1">
<input id="opnamenummer8" class="form-control" type="text" name="opnamenummer8" value="" maxlength="1">
</span>
<script type="text/javascript">
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
// if we've filled up this input, go to the next if only numerics are entered.
if ( (currentLength == maximumLength) && ((event.which >= 48 && event.which <= 57) || (event.which >= 96 && event.which<= 105))) {
$this.next().select();
}
//go to previous input if Backspace or Delete buton is pressed
if(event.which == 8 || event.which == 46) {
$(this).val('');
$(this).prev('input').select();
}
});
</script>
Don't use next(), use eq() and add or subtract to the index
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
if ( (currentLength == maximumLength) && (!isNaN(this.value))) {
$('input').eq($(this).index('input') + 1).select();
}
if(event.which == 8 || event.which == 46) {
$(this).val('');
$('input').eq($(this).index('input') - 1).select();
}
});
FIDDLE

Validate numbers in Javascript

How can I validate only the numbers 0 to 10?
I have this function which validate all the numbers.
function compruebacampo(e, campotexto) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
}
Thanks a lot for your help.
http://jsfiddle.net/6faHh/
The best JavaScript is no JavaScript.
<input type="number" min="0" max="10" />
<input id="your_input_id1" type="number" min="0" max="10" />
<input id="your_input_id2" type="number" min="0" max="10" />
<script>
var input1 = document.getElementById("your_input_id1");
var input2 = document.getElementById("your_input_id2");
function testNums(evt) {
var num = parseInt(evt.target.value, 10);
if (typeof num === "number" && num < 11 && num > -1) {
evt.target.value = num
} else {
evt.target.value = ''
}
};
input1.onkeyup = testNums;
input2.onkeyup = testNums;
</script>
Example js fiddle
http://jsfiddle.net/g63b5/3/
In this example entry is prevented and the box is cleared if the range is incorrect or anything other than number entered, also uses native html5 input for supported devices.
Edit: wasn't 100% sure what your comment meant, so I just added the handler to more inputs, in case that is what you were asking.

Show error message in a tool tip

I've a user registration form and I want to show the password rules in small tool tip along with the validation message like invalid password or valid password.My password rule is it contains 7 letters, 1 digit and 1 upper case letter etc.
Currently I've both of these but showing it in two different tool tip how can I merge two and show it in a single one.
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
</html>
$("#test :input").tooltip({
// place tooltip on the right edge
position: "center right",
// a little tweaking of the position
offset: [-2, 10],
// use the built-in fadeIn/fadeOut effect
effect: "fade",
// custom opacity setting
opacity: 0.7
});
You can see a working example here
http://jsfiddle.net/ddrYp/6/
Here's a solution, you won't need to use both the tooltip and password error div.
http://jsfiddle.net/ddrYp/12/
But you may run into problems with this in the future because the tooltips are not uniquely identified. I'm not familiar with the plugin, but if you could add an individual ID to each tooltip, that's fix it for you. Once you do that, you could reference the tooltips by using their ID instead of $(".tooltip")... if you expand this to have multiple inputs when you do $(".tooltip").append(/*something*/) or $(".tooltip").HTML(/*something*/) you're going to modify every tooltip.. which may not matter, because only one is visible at a time... but it's still an inefficiency issue and a bit of a bug
Here's the example of the ebay password verification example that you were looking for:
http://jsfiddle.net/cFrpz/7/
Try this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Here you go :
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
$(".tooltip").append($("#password-error"));
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
http://jsfiddle.net/ddrYp/9/
I haven't tested this but it should be fine. From your working example, replace this:
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
with this:
$tooltip = $(".tooltip");
if(!valid && $tooltip.find("div.error").length < 1){
$tooltip.append("<div class='error'>"+$("#password-error").html()+"</div>");
}
else if(valid) {
$tooltip.find(".error").remove();
}

Limit number of lines in textarea and Display line count using jQuery

Using jQuery I would like to:
Limit the number of lines a user can enter in a textarea to a set number
Have a line counter appear that updates number of lines as lines are entered
Return key or \n would count as line
$(document).ready(function(){
$('#countMe').keydown(function(event) {
// If number of lines is > X (specified by me) return false
// Count number of lines/update as user enters them turn red if over limit.
});
});
<form class="lineCount">
<textarea id="countMe" cols="30" rows="5"></textarea><br>
<input type="submit" value="Test Me">
</form>
<div class="theCount">Lines used = X (updates as lines entered)<div>
For this example lets say limit the number of lines allowed to 10.
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
fiddle:
http://jsfiddle.net/XNCkH/17/
Here is little improved code. In previous example you could paste text with more lines that you want.
HTML
<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>
JS
jQuery('document').on('keyup change', 'textarea', function(e){
var maxLines = jQuery(this).attr('data-max');
newLines = $(this).val().split("\n").length;
console.log($(this).val().split("\n"));
if(newLines >= maxLines) {
lines = $(this).val().split("\n").slice(0, maxLines);
var newValue = lines.join("\n");
$(this).val(newValue);
$("#linesUsed").html(newLines);
return false;
}
});
For React functional component that sets new value into state and forwards it also to props:
const { onTextChanged, numberOfLines, maxLength } = props;
const textAreaOnChange = useCallback((newValue) => {
let text = newValue;
if (maxLength && text.length > maxLength) return
if (numberOfLines) text = text.split('\n').slice(0, numberOfLines ?? undefined)
setTextAreaValue(text); onTextChanged(text)
}, [numberOfLines, maxLength])
A much ugly , but somehow working example
specify rows of textarea
<textarea rows="3"></textarea>
and then
in js
$("textarea").on('keydown keypress keyup',function(e){
if(e.keyCode == 8 || e.keyCode == 46){
return true;
}
var maxRowCount = $(this).attr("rows") || 2;
var lineCount = $(this).val().split('\n').length;
if(e.keyCode == 13){
if(lineCount == maxRowCount){
return false;
}
}
var jsElement = $(this)[0];
if(jsElement.clientHeight < jsElement.scrollHeight){
var text = $(this).val();
text= text.slice(0, -1);
$(this).val(text);
return false;
}
});
For the React fans out there, and possibly inspiration for a vanilla JS event handler:
onChange={({ target: { value } }) => {
const returnChar = /\n/gi
const a = value.match(returnChar)
const b = title.match(returnChar)
if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
dispatch(setState('title', value))
}}
This example limits a textarea to 2 lines or 80 characters total.
It prevents updating the state with a new value, preventing React from adding that value to the textarea.

Categories

Resources