How do I make a javascript function a html attribute? - javascript

I have a javascript variable with parameters, but I don't know how to pass it into my html code. The javascript code is taken from https://gist.github.com/EvanHahn/2587465:
var caesarShift = function(str, amount) {
// Wrap the amount
if (amount < 0)
return caesarShift(str, amount + 26);
// Make an output variable
var output = '';
// Go through each character
for (var i = 0; i < str.length; i ++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if ((code >= 65) && (code <= 90))
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if ((code >= 97) && (code <= 122))
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
I want to pass it on to my HTML obviously. I have done some research, and have come across ways such as:
<p id="output"></p>
and then
document.getElementById('output').innerHTML = lengthOfName;
but I don't know how to add it all together. How do I call the variable? For the string, I have a text area input box, and maybe a clicker for the second argument, the amount, but I don't know how to put it all together in the HTML.

You'll need to up the JavaScript inside a script tag and the p tag that you are getting by id in the body of an html document, like so:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<form id="form">
<div>
<label for="str">String:</label>
<input id="str" />
</div>
<div>
<label for="amount">Amount:</label>
<input id="amount" />
</div>
<button type="submit">Submit</button>
</form>
<p>CaesarShift: <span id="output"></span></p>
<script>
var caesarShift = function (str, amount) {
// Wrap the amount
if (amount < 0) return caesarShift(str, amount + 26);
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90)
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if (code >= 97 && code <= 122)
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
let str = document.getElementById("str").value;
let amount = parseInt(document.getElementById("amount").value);
let output = document.getElementById("output");
console.log(amount);
if (!amount) {
output.innerHTML = `<span style="color: red">Amount not valid</span>`;
return;
}
output.innerHTML = caesarShift(str, parseInt(amount));
}
</script>
</body>
</html>
See the snippet below with a working example:
var caesarShift = function(str, amount) {
// Wrap the amount
if (amount < 0) return caesarShift(str, amount + 26);
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90)
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
// Lowercase letters
else if (code >= 97 && code <= 122)
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
// Append
output += c;
}
// All done!
return output;
};
const handleSubmit = (e) => e.preventDefault();
const updateResult = () => {
amount = parseInt(document.getElementById("amount").value);
let output = document.getElementById("output");
if (!amount) {
output.innerHTML = `<span style="color: red">Amount not valid</span>`;
return;
}
output.innerHTML = caesarShift(
document.getElementById("text").value,
parseInt(amount)
);
};
const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);
let text = document.getElementById("text");
text.addEventListener("keyup", updateResult);
text.addEventListener("blur", updateResult);
let amount = document.getElementById("amount");
amount.addEventListener("change", updateResult);
amount.addEventListener("blur", updateResult);
<form id="form">
<div>
<label for="text">Text:</label>
<textarea id="text"></textarea>
</div>
<div>
<label for="amount">Amount:</label>
<input id="amount" />
</div>
</form>
<p>CaesarShift: <span id="output"></span></p>

Related

How do I keep this from going over the acii value of capitals

My if statement seems to no be working and i am confused to as of why. I need to keep the ascii value of "newcode" from going higher than the ascii value of the capitals.
document.getElementById("message").innerHTML = ("<h2> </h2>");
var msg= prompt("Enter your message." , " ");
var newmsg = " ";
var upCaseCode = 155;
var newCode = 0;
var usercode = 0;
var lowCaseCode = 219;
var specialCode = 3;
var random_num = (Math.floor(Math.random() * 10)) + 1;
console.log(random_num);
//the loop encodes each letter in the message string
for (var j = 0; j < msg.length; j++)
{
//check for upppercase letters and encode them
if ((msg.charCodeAt(j) >= 65) && (msg.charCodeAt(j) <= 90))
{ usercode = (random_num + msg.charCodeAt(j));
if (usercode >= 91)
{
newcode = usercode - 26;
}
else (usercode <= 64)
{
newcode = usercode + 26;
}
usercode = newCode;
console.log(newCode)
}
else
//check for lowercase letters and encode them
if ((msg.charCodeAt(j) >= 97) && (msg.charCodeAt(j) <= 122))
{ newcode = ((lowCaseCode + random_num) - msg.charCodeAt(j)); }
else
//check for numbers and special characters and encode them
if (((msg.charCodeAt(j) > 90) && (msg.charCodeAt(j) < 97)) || (msg.charCodeAt(j) < 65))
{ newcode = (msg.charCodeAt(j) + specialCode); }
//add each encoded character to the new message
newmsg = newmsg + " " + String.fromCharCode(newcode);
}

JavaScript to format account number

I have to format an account number input field like below:
Desired format: 123456 1234 12 1
But, the regex which I wrote formats the text field as below:
Current format: 1234 1234 1234 1
Can someone please help me with the correct regex or logic to implement this?
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 4) {
parts.push(match.substring(i, i + 4))
}
if (parts.length) {
return parts.join(' ')
} else {
return value
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can get groups of 6, instead of groups of 4, then, as soon as your second group gets over 4 characters long, you can insert a space at the desired position. Here's a proof of concept:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{6,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 6) {
parts.push(match.substring(i, i + 6))
}
if (parts.length > 1 && parts[1].length > 4) {
parts[1] = [parts[1].slice(0, 4), ' ', parts[1].slice(4)].join('');
}
if (parts.length) {
return parts.join(' ')
} else {
return v
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
A slightly more elegant solution would be to use .slice() and .join() for the whole thing, which cleans up the code nicely. Here's an example:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
if (v.length > 6)
v = [v.slice(0, 6), ' ', v.slice(6)].join('');
if (v.length > 11)
v = [v.slice(0, 11), ' ', v.slice(11)].join('');
if (v.length > 14)
v = [v.slice(0, 14), ' ', v.slice(14)].join('');
if (v.length > 16)
v = v.slice(0, 16);
return v;
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can use following code, to format the code properly when user is typing. It works dynamically.
const normalize = elem => {
let value = elem.target.value;
const onlyNums = value.replace(/[^\d]/g, '');
if (onlyNums.length <= 6) {
return onlyNums;
} else if (onlyNums.length <= 10) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6)}`;
} else if (onlyNums.length <= 12) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}`;
}
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}
${onlyNums.slice(12, 13)}`;
};
const input = document.getElementById('input');
input.addEventListener('input', (e) => e.target.value = normalize(e));
<input type='text' id='input' value=''>

Trying to print the right answer in Javascript using getElementById

I'm trying to find whether or a not a number is a perfect number, but I can't get it to print right. The numbers 6, 496, 8128 are perfect numbers but when I entered those it kept printing from var res2 instead of var res1. What's the problem here, can anyone can help?
function perfectNo(number) {
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>
Try with :
var number = document.getElementById("num").value;
Like this :
function perfectNo() {
var number = document.getElementById("num").value;
console.log(number);
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>

Credit card validation in javascript

I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/

Use jquery or javascript to add commas to disabled field

I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.

Categories