I'm using normal JS and JSP which contains normal HTML tags. I have an input field with the type as PASSWORD which contains the maxlength of 10 digits.
Now I want to display the last 4 digits of the field values and other digits should be masked.
I'm not using jQuery and I want to use in normal JS.
So can anyone please suggest me any approach on it to achieve.
Try following these steps.
Get the password value.
Get the 2 parts (last 4 characters and the remaining leading characters).
Replace the leading characters with • (ASCII-7 character).
Generate new password to show (masked + 4 visible characters).
Set the password value.
Check out this fiddle.
Here is the snippet.
var passField = document.getElementById('pass');
passField.type = "text";
var passValue = passField.value;
var passLength = passValue.length;
var masked = passValue.substring(0, passLength - 4);
masked = masked.replace(/./g, '•'); //The character is ASCII-7 (Press Alt+7 to type)
var text = passValue.substring(passLength - 4);
var newPass = masked + text;
passField.value = newPass;
<input type='password' id='pass' value="ThisIsPassword" />
CSS
#wrapper {
position: relative;
}
#wrapper > input {
font-family: monospace;
text-align: right;
}
#wrapper > [type=password]::-ms-reveal{
display: none;
}
#passwordMasked {
width: 10em;
border: solid 1px black;
border-right: none;
}
#wrapper > #passwordUnmasked {
border: solid 1px black;
border-left: none;
width: 3em;
text-align: left;
}
#password {
position: absolute;
left: 0;
opacity: 0;
width: 13em;
}
HTML
<div id="wrapper">
<input type="password" onkeyup="updateunmasked()" id="passwordMasked" /><input type="text" id="passwordUnmasked" readonly /><input type="password" onkeyup="updateunmasked()" id="password" />
</div>
Javascript
function updateunmasked() {
var p = document.getElementById("password").value;
document.getElementById("passwordUnmasked").value = (' ' + p.substring(Math.max(p.length - 4, 0))).substring(Math.min(p.length, 4));
document.getElementById("passwordMasked").value = p.substring(4);
}
JSBin - https://jsbin.com/wijifupuco/1/edit?html,css,js,output
Related
I have a revenue input field in a javascript/jquery form:
Need a dollar sign :before
add commas as the currency increases
I have a dollar sign showing via css, but issues centering it and ensuring the field entry point is next to it without overlapping. Unsure how to do the commas. Any suggestions or tips are welcome!
HTML:
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
<br>
</form>
CSS:
<style>
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left:30px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px;
color: black;
}
</style>
JS:
<script>
$('#rev-calculator').on('click', 'button', function(e) {
e.preventDefault();
var price = $("#price").val();
console.log(price);
})
</script>
codepen: https://codepen.io/kedarPE/pen/JjroYyb
input field
Well here's a way, though in truth not as simple as I hoped when I started down this path. You can use Intl.NumberFormat to get the comma in there (according to locale). To accomodate decimals, I sniff for them in the beginning and append them to the result.
To allow for the comma, I made this a text field with a pattern attribute. Also, I adjusted your CSS to make it a little nicer looking with the $
$('#price').keydown(function(e) {
setTimeout(() => {
let parts = $(this).val().split(".");
let v = parts[0].replace(/\D/g, ""),
dec = parts[1]
let calc_num = Number((dec !== undefined ? v + "." + dec : v));
// use this for numeric calculations
// console.log('number for calculations: ', calc_num);
let n = new Intl.NumberFormat('en-EN').format(v);
n = dec !== undefined ? n + "." + dec : n;
$(this).val(n);
})
})
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left: 35px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px 10px 10px 20px;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" />
<br>
</form>
I'm surprised the unique answer for this issue has a lot of votes because it has a tiny but major flaw: the event shouldn't be keydown, it should be keyup. If you use keydown, it won't read the keys you are pressing at the moment but the previous one. So, please update your answer.
I have created an application to calculate BMI. Basically, here is how I'd like the application to work and wrote below so far:
You just enter your height in inches and enter weight in pounds.
The application will calculate your BMI, then tell you whether you are underweight, normal, obese, or overweight.
In case you enter a non-positive value for either height or weight, the program will show you an error message that "Invalid input. Enter a positive number.", and it will highlight the boxes that you need to fix/enter a valid value.
I have encountered 2 problems.
I can get the program to show the BMI result, but currently I don't know how to write to get the program to show whether the user is underweight, normal, obese, or overweight.
If BMI < 18.5 then underweight, BMI >= 18.5 and <=24.99 then normal, BMI > 25 and <=29.99 then obese, and BMI > 30 then overweight.
I would like to show the error (that tells user to enter positive values, not missing or negative values) as messages below the "Calculate BMI" button, not as an alert like "This page says - Invalid input for weight, enter a non-negative number." In other words, I would like to keep the same message but not using "alert" method.
How may I fix these problems please? I have attached both my HTML and my CSS codes below.
Thank you so much!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid) //calculate BMI
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
if (outputBMI[0]<18.5) outputBMI[0].textContent = "Your BMI indicates that you are underweight.";
if (outputBMI[0]>=18.5 && outputBMI[0]<=24.99) document.getElementById("result").value = "Normal";
if (outputBMI[0]>=25 && outputBMI[0]<=29.99) document.getElementById("result").value = "Obese";
if (outputBMI[0]>30) document.getElementById("result").value = "Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>
Here is my CSS code also, if you need it:
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}
There's a lot to rework on your code. But the bottom line is that you need to remember that a classSelector (in your case results) always return an array. Switch to an Id if you're using an unique dom
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var resultElm = document.getElementById("result");
resultElm.textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
var bmi = 703 * weight / (height** 2)
if (valid) //calculate BMI
{
resultElm.textContent ="Your BMI is: " + (bmi).toFixed(1);
if (bmi<18.5) resultElm.textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) resultElm.textContent += " Your BMI indicates that you are Normal.";
if (bmi>=25 && bmi<=30)resultElm.textContent += " Your BMI indicates that you are Obese.";
if (bmi>30) resultElm.textContent += " Your BMI indicates that you are Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div id="result"></div>
</main>
After a while, I have edited my code several times and this is a version that I think is worth sharing. I know that there are still quite some edits to do - but here it is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
var height = heightInputBox.value;
height = parseFloat(height);
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid)
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
//This is just for my trial and learning process. =)
var bmi = (703 * weight / (height*height)).toFixed(1);
if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
}
};
//handler button click event
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>
I know this question already has a good and valid answer.
The following is simply the result of me playing around with the fiddle, trying to shorten it and make it more "responsive".
I removed the calculate button and use eval() now to tolerantly convert and calculate the input fields' values.
const qs=s=>document.querySelector(s);
evl=s=>{var v='', el=qs(s);
try{v=eval(el.value)||''} catch(er){v=''}
el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
return v
}
var scale=[[18.5,"underweight"],
[25,"normal"],[30,"obese"],
[31,"seriously overweight"]];
qs("body").addEventListener("keyup",ev=>{if(ev.target.type!='text') return;
var txt, height=evl("#boxHeight"), weight=evl("#boxWeight");
if (height>0 && weight>0){
BMI=703*weight/(height*height);
scale.every(sc=>(txt=sc[1],BMI>sc[0]));
txt='Your BMI of '+BMI.toFixed(1)+" indicates<br>that you are "+txt+".";
} else txt='';
qs("#result").innerHTML=txt
});
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {margin-left:20px;
font-size:1.5ex;}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight' placeholder="value or formula"/><span id="one"></span><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight' placeholder="value or formula"/><span id="two"></span><br>
<div id="result"></div>
</main>
I have made a text box, which i enter text into and it gets printed out in a div below as it is typed. Currently, the DIV can fit 24 characters into it and then i have the text to wrap. What i'm trying to do is to get the DIV to double in height for every 24 characters that are entered.
I want to do this using only Javascript and no jQuery
<div class="one">Input Some Text
<form>
<input type="text" id="pointlessInput"/>
<script>
var stringToBePrinted = document.getElementById("pointlessInput");
var len = stringToBePrinted.length;
stringToBePrinted.onkeyup = function(){
var len = stringToBePrinted.length;
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
if(document.getElementById("pointlessInput").innerHTML.value.length == 24){
document.getElementById("printbox").style.height = "4em";
}
}
</script>
</form>
<div class="printbox" id="printbox"></div>
</div>
stylesheet
.printbox {
border-width:thick 10px;
border-style: solid;
background-color:#fff;
line-height: 2;
color:#6E6A6B;
font-size: 14pt;
text-align:center;
border: 3px solid #969293;
width:50%;
height:2em;
margin: auto;
word-wrap: break-word;
}
var stringToBePrinted = document.getElementById("pointlessInput");
stringToBePrinted.onkeyup = function() {
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
var multiple = Math.ceil(parseInt(document.getElementById("pointlessInput").value.length) / 24);
document.getElementById("printbox").style.height = (multiple * 2) + "em";
}
Remove the if condition and the height from the css, it works just fine.
Check the below working example.
var stringToBePrinted = document.getElementById("pointlessInput");
var len = stringToBePrinted.length;
stringToBePrinted.onkeyup = function(){
var len = stringToBePrinted.length;
document.getElementById("printbox").innerHTML = stringToBePrinted.value;
}
.printbox {
border-width:thick 10px;
border-style: solid;
background-color:#fff;
line-height: 2;
color:#6E6A6B;
font-size: 14pt;
text-align:center;
border: 3px solid #969293;
width:50%;
margin: auto;
word-wrap: break-word;
}
<div class="one">Input Some Text
<form>
<input type="text" id="pointlessInput"/>
<script>
</script>
</form>
<div class="printbox" id="printbox"></div>
</div>
I want to put empty spaces after a letter while typing.
We can make it with css letter-spacing property but when we copy this text, i does not keep white spaces.
How can we make it with vanilla javascript?
Added letter-spacing to my css to show what i want exaclty.
JSFIDDLE
var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");
my_text.addEventListener("keyup", function() {
var val = this.value;
output_text.innerHTML = val;
});
#output_text {
width: 300px;
height: 200px;
border: 1px solid #ccc;
letter-spacing: 10px;
}
<textarea id="my_text" cols="30" rows="10"></textarea>
<div id="output_text"></div>
Split all the characters and join with a white space: https://jsfiddle.net/wkw72u7e/4/.
var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");
my_text.addEventListener("keyup", function() {
output_text.innerHTML = this.value.split('').join(' ');
});
#output_text {
width: 300px;
height: 200px;
border: 1px solid #ccc;
}
And why vanilla javascript? Ordinary javascript can do it:
var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");
my_text.addEventListener("keypress", function(event) {
event.preventDefault();
output_text.innerHTML += " " + String.fromCharCode(event.keyCode);
});
#output_text {
width: 300px;
height: 200px;
border: 1px solid #ccc;
}
<textarea id="my_text" cols="30" rows="10"></textarea>
<div id="output_text"></div>
The following code create a web page form. It asks a user to enter a character in an input box, then a sentence in an another box. Then the user should be able to click in a button to count the number of times the character appeared in the sentence entered in the second input box. The sentence should include only letters . The problem I am having is that I am having an error message saying that I entered non alphabets in the box, although i enter only characters!
Any idea why this is happening please !
Here is my HTML / javascript code:
//<![DATA[
'use strict';
function updateForm(id) {
var letter = "";
var sentence = "";
var occurencies = 0;
var form = document.getElementById(id);
letter = form.box1.value;
sentence = form.box2.value;
for (var i = 0; i < sentence.length; i++)
if (sentence.charAt(i) == letter)
occurencies++;
form.box3.value = occurencies;
}
function isAlphabet(elem, helperMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
} //-->
body {
background-color: lightblue;
}
form {
width: 500px;
margin: 0 auto;
}
h4 {
font-family: sans-serif;
font-size: xx-large;
text-align: center;
}
h1,
h2,
h3 {
font-family: sans-serif;
font-style: italic;
font-size: large;
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
font-style: italic;
}
input[type="button"] {
background: #B9DFFF;
color: #fff;
border: 10px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
position: absolute;
left: auto;
}
input[type="button"]:hover {
background: #016ABC;
color: #fff;
border: 5px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
}
<form action="#" id="boxes">
Box 1:
<input type="text" name="box1" value="" placeholder="Enter a single
letter" maxlength="1" />
<li class="rq">Only alphabet letters are allowed.</li>
<br />Box 2:
<input type="text" name="box2" value="" placeholder="Enter a sentence" />
<br />Result:
<input type="text" id="letters" name="box3" readonly />
<br />
<input type="button" name="update" value="Update" onclick="isAlphabet(document.getElementById('letters'), 'Only Letters are allowed')" />
</form>
You are checking the wrong form field:
onclick="isAlphabet(document.getElementById('letters')...
As I understand you want to check box1 not 'box3/letters'...
Add id='box1' to that input element and then check like this:
onclick="isAlphabet(document.getElementById('box1')...
You code seems to be fine, just try and trim the element value before you match the same
if (elem.value.trim().match(alphaExp)) {
return true;
}
ensure that you are passing right value to this isAlphabet function
<input type="button" name="update" value="Update" onclick="isAlphabet(document.getElementById('box1'), 'Only Letters are allowed')" />
to count the number of occurences
letter = form.box1.value;
sentence = form.box2.value;
var occurences = sentence.split( letter ).length - 1;
Only the isAlphabet function is called in this code. And it checks an empty field. Your onclick attribute is addressed to that element.
onclick="isAlphabet(document.getElementById('letters'), 'Only Letters are allowed')"
It is holding an empty string when the isAlphabet function is called. An empty string is non-alphanumeric so it returns false.
As robert mentions, you need to include a reference to box1 or box2 in your call to isAlphabet as this is it's input. That is if you need to call it at all.
Also, I can't see a call to you main updateForm function anywhere. Unless this is not the full code, you need to include that. For example, you could do...
<input type="button" name="update" value="Update" onclick="isAlphabet(getElementById('box1, box2'))" />
with those parameters passed to the function.
Because they are passed to the function you don't need to declare them, they are right there for you to use.
You can also just include the validation within this function. To alert if it's non alphabetic.
function updateForm(letter, sentence) {
var occurences = 0;
var form = document.getElementById(id);
for (var i = 0; i < sentence.length; i++) {
if (sentence.charAt(i) == letter) {
occurences++;
}
}
if(letter.match(alphaExp) && sentence.match(alphaExp)) {
..do the thing..
} else {
alert('Only Letters are allowed');
}
}