So basically I am having trouble converting an input value into a string.
HTML:
<input type="text" placeholder="Email Ex: john321" id="grailedemail">
<input type="text" placeholder="Domain Ex: #gmail.com" id="graileddomain">
JS:
let email = document.getElementById("grailedemail").value;
let domain = document.getElementById("graileddomain").value;
let _ge = grailed_email.toString();
let _gd = grailed_domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
I dont know if this is the right use of .toString method.
The output of the above returns this:
{
"email":"+388321",
"pass":"password",
}
Expected Output:
{
"email":"johndoe+388321#gmail.com",
"pass":"password",
}
(I want to get whatever the user inputs)
Where before the plus there is supposed to be the variable _ge or email
And after the number, there is supposed to be the variable _gd or domain
Your problem is a typo.
The variable that contains the email is the email, and the variable that contains the domain is the domain, but you're using grailed_email and grailed_domain, and that's why the wanted data isn't in the string. Change your code to:
let grailed_email = document.getElementById("grailedemail").value; // Variable grailed_email fixed
let grailed_domain = document.getElementById("graileddomain").value; // Variable grailed_domain fixed
let _ge = grailed_email.toString();
let _gd = grailed_domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
try this way
function debug() {
var email = document.getElementById("grailedemail").value;
var domain = document.getElementById("graileddomain").value;
var _ge = email.toString();
var _gd = domain.toString();
let randNum = Math.floor(Math.random() * 999999) + 1;
let emailAltered = `${_ge}+${randNum}${_gd}`;
document.getElementById('debug').textContent = emailAltered;
}
<input type="text" value="Johndoe" placeholder="Email Ex: john321" id="grailedemail">
<input type="text" value="#gmailcom" placeholder="Domain Ex: #gmail.com" id="graileddomain">
<input type="button" onclick="debug()" value="Submit">
<p id="debug"></p>
Related
Encryption is working but decryption is not working at all and I am not able to spot my mistake
In javascript I have four functions:
First two encrypt and decrypt the text with or without key, Probably there is nothing wrong in first two functions
In third and fourth function I am taking input from html page and by storing them in variable I am encrypting and decrypting them
function encrypt(message = '', key = '') { //This function will take message and key for encryption
var x = CryptoJS.AES.encrypt(message, key);
return x.toString();
}
function decrypt(message = '', key = '') { //This function will take message and key for decryption
var y = CryptoJS.AES.decrypt(message, key);
var decryptedMessage = decry.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
function AesEncrypt() {
const text = document.getElementById('inputText').value;
const password = document.getElementById('inputPassword').value;
var x = encrypt(text, password);
document.getElementById("demo1").innerHTML = x;
}
function AesDecrypt() {
const text1 = document.getElementById('inputText').value;
const password2 = document.getElementById('inputPassword').value;
var x1 = decrypt(text1, password2);
document.getElementById("demo2").innerHTML = x1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<input type="text" id="inputText" placeholder="Enter Plain text or Text to Decrypt">
<input type="text" style="width: 100%;" id="inputText" placeholder="Enter Plain text or Text to Decrypt">
<input type="text" id="inputPassword" placeholder="Enter a Key">
<button type="button" onclick="AesEncrypt()">Encrypt</button>
<button type="button" onclick="AesDecrypt()">Decrypt</button>
<p id="demo1"> </p>
<p id="demo2"> </p>
You made two mistakes
X decry.toString(CryptoJS.enc.Utf8);
O y.toString(CryptoJS.enc.Utf8);
X const text1 = document.getElementById('inputText').value;
O const text1 = document.getElementById('demo1').innerHTML;
You are using same id for two elements, and it's bad practice.
This is working code.
<input type="text" id="inputText" placeholder="Enter a Text">
<input type="text" id="inputPassword" placeholder="Enter a Key">
<button type="button" onclick="AesEncrypt()">Encrypt</button>
<button type="button" onclick="AesDecrypt()">Decrypt</button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<script src="crypto-js.js"></script>
<script>
function encrypt(message = '', key = '') { //This function will take message and key for encryption
var x = CryptoJS.AES.encrypt(message, key);
return x.toString();
}
function decrypt(message = '', key = '') { //This function will take message and key for decryption
var y = CryptoJS.AES.decrypt(message, key);
var decryptedMessage = y.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
function AesEncrypt() {
const text = document.getElementById('inputText').value;
const password = document.getElementById('inputPassword').value;
var x = encrypt(text, password);
document.getElementById("demo1").innerHTML = x;
}
function AesDecrypt() {
const text1 = document.getElementById('demo1').innerHTML;
const password2 = document.getElementById('inputPassword').value;
var x1 = decrypt(text1, password2);
document.getElementById("demo2").innerHTML = x1;
}
</script>
Hi thanks everyone for your answers, I have fixed the problem now it was a variable mistake.
The source code is available in github : https://github.com/iArchitSharma/Encrypt-Decrypt-Text
Any kind of contributions are welcome
I want to display contents in the last <div> element when a click event occurs but now it only shows 1st 2 elements. Is there something I am not doing right somewhere?
Here is my code so far:
JS
const iname = document.getElementById("name");
const iemail = document.getElementById("email");
const iphone = document.getElementById("phone");
const submit = document.getElementById("submit");
const storage = document.getElementById("storage");
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
localStorage.setItem(name, "");
localStorage.setItem(email, "");
localStorage.setItem(phoneno, "");
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `Name : ${key}<br />Email : ${value}`;
}
localStorage.clear()
HTML
<p>Name</p>
<input id="name" autocomplete="off">
<p>Email</p>
<input id="email" autocomplete="off">
<p>Phone no</p>
<input id="phone" autocomplete="off">
<button id="submit">Let's go</button>
<div id="storage" class="box">
<h1>Is this correct?</h1></div>
I think you are setting the values in localstorage the wrong way.
The syntax for storing stuff in there is localstorage.setItem(keyName, keyValue).
And your code is setting the keyName argument to the value you are getting from the form and keyValue argument to an empty string; not what you need.
Make the following changes and you should be good to go (see comments):
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
// set local storage values
localStorage.setItem("name", name); // modified
localStorage.setItem("email", email); // modified
localStorage.setItem("phoneno", phoneno); // modified
location.reload();
}
console.log(localStorage); // new (maybe unnecessary)
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `${upFirst(key)}: ${value}<br>`; // modified
}
localStorage.clear();
/**
* new: making the first letter an upper case (for labels in the output div).
* See usage in 'for loop' above.
*/
function upFirst(stringValue) {
return stringValue.slice(0, 1).toUpperCase() + stringValue.slice(1);
}
I'm making a tip calculator and I would like the tip amount to display for the user to see. The problem I'm having is the output showing up as 'NaN' or 'undefined'. I've tried making changes to my code but I keep getting the same result.
function calculateTip() {
var billInput = document.getElementById('bill');
var tipPercentage = document.getElementById('tip');
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', +tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You forgot to get the value of your fields. Because without the property .value, it returns HTMLObject.
function calculateTip() {
var billInput = parseFloat(document.getElementById('bill').value);
var tipPercentage = parseFloat(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;
};
You are reading billInput and tipPercentage as HTML element objects instead of the text the user types into them, which will be their .value properties.
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You're loading the element instead of the element value when declaring the variables billInput and tipPercentage. Try with this code:
var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;
I am trying to put some amount, then it will show the calculation if all input will given any number, but I want, when I do not put anything in any one of that input, then the input will count "0" automatically..
<body>
<input type='text' id='aaa'/>
<input type='text' id='bbb'/>
<input type='text' id='ccc'/>
<input type='text' id='answer' name='ans' />
<form name ="testarea" Method="GET" Action="" id='form1'>
<input type="button" onClick="Calculate();" value="calculate"/>
</form>
</body>
<script>
function Calculate()
{
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = parseFloat(aaa) * 82;
var permin1 = parseFloat(bbb) * 40;
var permin2 = parseFloat(ccc) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
document.form1.submit();
}
</script>
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = (parseFloat(aaa)||0) * 82;
var permin1 = (parseFloat(bbb)||0) * 40;
var permin2 = (parseFloat(ccc)||0) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
You can use the OR operator to replace NaN with 0 if parseFloat returns NaN.
You could shorten the upper code to:
const ids = ["aaa","bbb","ccc"];
const factors = [82,40,10];
document.getElementById("answer").value = ids.reduce((count,id,index) => {
const { value } = document.getElementById(id);
return count + (parseFloat(value) || 0) * factors[index];
}, 0);
An alternative you can do is use a default parameter for your function.
Your calculate would look something like this:
Calculate(aaa=0, bbb, ccc) {
And this question covers how to pass html elements as parameters for functions.
Instead of using an if/else construct you can rely on the falsy value of an empty string.
Therefore you can initialize all your variables like this:
var aaa = document.getElementById('aaa').value || '0';
More information on falsy values can be found on the MDN.
Ok, I have these input boxes.
<input
type="text"
name="amount"
class="validate[required] text-input"
id="amount">
<input type="text"
name="incfee"
id="incfee"
readonly>
And this is the javascript I have :-
<script type="text/javascript">
window.onload = function() {
var amount = document.getElementById('amount');
var incfee = document.getElementById('incfee');
var fee = 0.01;
amount.onkeyup = function() {
var result = parseFloat(amount.value) * fee;
// var result1 = result + amount;
incfee.value = !isNaN(result) ? result : '';
};
}
</script>
Now, the problem is, that if I comment the line "var result1 = result + amount;" and rename result1 to result in incfee.value , the value of the textbox (amount including fee) changes with the value in amount and everything works fine.
BUT, If I uncomment the line var result1 = result + amount; and change result to result 1 in incfee.value, the javascript doesn't works and no value is populated in the incfee textbox.
What mistake am I doing?
Thanks.
var result1 = result + parseFloat(amount.value);
Javacript doesnt know how to add a float and an input-object.
Use .value to get value of input text
var amount = document.getElementById('amount').value;
var incfee = document.getElementById('incfee').value;