Bad Javascript Coding and Drop Down Boxes - javascript

here is a jsfiddle I made to show you what I'd like help with.
Need help with updating select box values
I've tried using 3 for loop constructs to update my drop down box, but my bad Javascript skills don't let me achieve this.
var units = [
['Volts', 1],
['Millivolts', .001],
['Microvolts', 0.000001]
];
var selectors = document.querySelectorAll('.Voltage');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
var units = [
['Amps', 1],
['Milliamperes', .001],
['Microamperes', 0.000001]
];
var selectors = document.querySelectorAll('.Current');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
var units = [
['Ohms', 1],
['Milliohms', .001],
['Microohms', 0.000001]
];
var selectors = document.querySelectorAll('.Resistance');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if (Resistance != "0" && Current != "0") {
document.getElementById("inputVoltage").value = parseFloat(Current * Resistance).toExponential();
}
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if (Voltage != "0" && Resistance != "0") {
document.getElementById("inputCurrent").value = parseFloat(Voltage / Resistance).toExponential();
}
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if (Voltage != "0" && Current != "0") {
document.getElementById("inputResistance").value = parseFloat(Voltage / Current).toExponential();
}
}
<!DOCTYPE html>
<html>
<body>
<br>
<select style="float:left" id="EANDM1" class="js-example-basic-single select2-container Voltage" oninput="EqualsResistance(); EqualsCurrent()" onchange="EqualsResistance(); EqualsCurrent()">
</select>
<label>Voltage:</label>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="inputVoltage" type="number" oninput="EqualsResistance(); EqualsCurrent()" value="0"> </p>
<select style="float:left" id="EANDM2" class="js-example-basic-single select2-container Current" oninput="EqualsVoltage(); EqualsResistance()" onchange="EqualsVoltage(); EqualsResistance()">
</select>
<p>
<label>Current:</label>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="inputCurrent" type="number" oninput="EqualsVoltage(); EqualsResistance()" value="0"> </p>
<select style="float:left" id="EANDM3" class="js-example-basic-single select2-container Resistance" oninput="EqualsCurrent();EqualsVoltage()" onchange="EqualsCurrent();EqualsVoltage()">
</select>
<p>
<label>Resistance:</label>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="inputResistance" type="number" oninput="EqualsCurrent();EqualsVoltage()" value="0"> </p>
</body>
</html>
When I switch to millivolts in the drop down box, the values for Current and Resistance should change after I've filled in 2 values in their respective drop down boxes. Please help me get the drop down box to change the values for the input fields. Thank you.

There's a couple problems.
parseFloat(Current * Resistance)
This doesn't work because Current and Resistance are strings, but you're multiplying them before you parse them. Instead, parse them before you multiply them:
parseFloat(Current) * parseFloat(Resistance)
Another problem, related to the recalculation when selecting something from one of the drop-down boxes, is that you aren't pulling out or using the factors. So the units never change.
Here is a quick tidying up I did of the calculation code that takes into account the selected units and converts values before doing the calculation. (I also removed the toExponential calls to see what was happening a bit more easily.)
Extracted the code that gets the values from the controls to its own function. This could still be improved further.
function GetValues() {
const voltageText = document.getElementById("inputVoltage").value;
const currentText = document.getElementById("inputCurrent").value;
const resistanceText = document.getElementById("inputResistance").value;
const voltageFactorText = document.getElementById("EANDM1").value;
const currentFactorText = document.getElementById("EANDM2").value;
const resistanceFactorText = document.getElementById("EANDM3").value;
const voltageValue = parseFloat(voltageText);
const currentValue = parseFloat(currentText);
const resistanceValue = parseFloat(resistanceText);
const voltageFactor = parseFloat(voltageFactorText);
const currentFactor = parseFloat(currentFactorText);
const resistanceFactor = parseFloat(resistanceFactorText);
const voltage = voltageValue / voltageFactor;
const current = currentValue / currentFactor;
const resistance = resistanceValue / resistanceFactor;
return [voltage, current, resistance];
}
And then the three recalculation functions:
function EqualsVoltage() {
const [voltage, current, resistance] = GetValues();
if (!resistance || !current)
return;
document.getElementById("inputVoltage").value = current * resistance;
}
function EqualsCurrent() {
const [voltage, current, resistance] = GetValues();
if (!voltage || !resistance)
return;
document.getElementById("inputCurrent").value = voltage / resistance;
}
function EqualsResistance() {
const [voltage, current, resistance] = GetValues();
if (!voltage || !current)
return;
document.getElementById("inputResistance").value = voltage / current;
}

Related

Web page displays and animated times table

Hi everyone I am currently stuck trying to debug my program. MY goal is for whenever the button "Start Animation" is clicked, the web page displays an animated times table according to the number that the user enters in the text field in the following manner. For example, if the user entered the number 6 in the text field, then the animation displays 1 x 6 = 6, one second later it replaces it with 2 x 6 = 12, one second later it replaces it with 3 x 6 = 18, etc. If it is 9 x 6 = 54, then one second later it becomes 1 x 6 = 6, and then 2 x 6 = 12, and so on.
var counter;
var animationOn = false;
var counterAnimation;
function updateAnimation() {
var value = document.getElementById('value1').value;
for (var i = 1; i < 1000; i++) {
for (var j = 1; j < 10; j++) {
var product = j * value;
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = product;
}
}
counterAnimation = setTimeout(updateAnimation, 1000);
}
function startAnimation() {
if (animationOn == false) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn == true) {
animationOn = false;
clearTimeout(updateAnimation);
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>
Edited
Here is a complete solution which makes changes displayed value by time
let counter;
let animationOn = false;
let counterAnimation;
let mult = 1;
function updateAnimation() {
let value = document.getElementById('value1').value;
let counterSpan = document.getElementById("counterHolder");
if (mult >= 10) {
mult = 1;
counter = null;
animationOn = false;
counterAnimation = null;
counterSpan.innerHTML = 0;
return;
}
let product = mult * value;
counterSpan.innerHTML = product;
mult++
counterAnimation = setTimeout(updateAnimation, 1000)
}
function startAnimation() {
if (!animationOn)
{
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn)
{
animationOn = false;
clearTimeout(counterAnimation);
mult = 1
counter = null
animationOn = false
counterAnimation = null
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>

How can I create a secret message app using the square code method?

I need to create a secret message app, such that a text:
"If man was meant to stay on the ground, god would have given us roots."
is normalized to:
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"
And the normalised text forms a rectangle (​r x c​) where ​c​ is the number of columns and ​r​ is the number of rows such that ​c >= r​ and ​c - r <= 1​,
So for instance the normalized text is 54 characters long, dictating a rectangle with ​c = 8​ and ​r = 7​:
"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots "
Then the coded message is obtained by reading down the columns going left to right
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
and further split to
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau"
The resulting cypher text for a non perfect rectangle can only have a single whitespace for the last rows.
"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"aohghn "
"sseoau "
This what I have done so far, I could only get my normalised text, but I am doing something wrong to convert it to a rectangle and to get a cypher text out of it.
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
function wordCount() {
return message.split(" ").length;
}
if (wordCount < 2 || message.length < 50) {
error.innerHTML = "Invalid message, Input more than one word and at Least 50 characters!";
return false;
}
function normaliseMessage() {
return message.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function rectangleSize() {
return Math.ceil(Math.sqrt(normaliseMessage.length));
}
function splitRegEx() {
return new RegExp(".{1," + rectangleSize + "}", "g");
}
function plaintextSegments() {
return normaliseMessage.match(splitRegEx);
}
function ciphertext() {
var columns = [],
currentLetter, currentSegment;
var i, j;
for (let i = 0; i < rectangleSize; i++) {
columns.push([]);
}
for (i = 0; i < plaintextSegments.length; i++) {
currentSegment = plaintextSegments[i];
for (j = 0; j < columns.length; j++) {
currentLetter = currentSegment[j];
columns[j].push(currentLetter);
}
}
for (i = 0; i < columns.length; i++) {
columns[i] = columns[i].join("");
}
return columns.join("");
}
function normalizeCipherText() {
return ciphertext.match(splitRegEx).join(" ");
}
text.innerHTML = plaintextSegments();
encodedChunks.innerHTML = ciphertext();
output.innerHTML = normalizeCipherText();
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks">
</p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle">
</p>
</div>
Most of your code is constructed of very short methods.
Usually I'd consider a good practice, but in this case I think it just made the code less readable.
Additionally, I have to say that the HTML part wasn't necessary in terms of solving the issue - which was clearly Javascript/algorithm related.
This is my solution, which can be modified to match your context:
const input = "If man was meant to stay on the ground, god would have given us roots.";
const normalizedInput = input.replace(/[^\w]/g, "").toLowerCase();
const length = normalizedInput.length;
const cols = Math.ceil(Math.sqrt(length));
const rows = Math.ceil(length / cols);
var cypherText = "";
for (let i = 0; i < cols; i ++) {
for (let j = i; j < normalizedInput.length; j += cols) {
cypherText += normalizedInput[j];
}
cypherText += '\n';
}
console.log(cypherText);
This is what I came up with
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
var normalisedText = message.replace(/[^a-zA-Z0-9]/g, "");
var textCount = normalisedText.length;
if (textCount < 50) {
console.log("Invalid message, Input more than one word and at Least 50 characters!");
return false;
}
var higest = Math.ceil(Math.sqrt(textCount));
var lowest = Math.ceil(textCount/higest);
var rect = [];
var coded = [];
var innerObj = {};
var resulting = "";
rect = rectangleSize(higest,lowest,normalisedText);
//read text from top-down i hotago!!!
coded = readFromTopDown(rect, higest);
coded.forEach(co => {
resulting += co.trim();
});
//nwa idi sharp, nice logic
console.log("Normalized: " + normalisedText);
console.log("Count: " + textCount);
console.log(rect);
console.log(coded);
console.log("Resulting: " + resulting);
function rectangleSize(higest, lowest, normalise) {
var rect = [];
var startIndex = 0;
for(var i = 0; i < lowest; i++){
if(i !== 0)
startIndex += higest;
if(normalise.substring(startIndex, startIndex + higest).length == higest){
rect.push(normalise.substring(startIndex, startIndex + higest))
}else{
//get the remainder as spaces
var spaces = higest - normalise.substring(startIndex, startIndex + higest).length;
var textI = normalise.substring(startIndex, startIndex + higest);
var str = textI + new Array(spaces + 1).join(' ');
rect.push(str);
}
}
return rect;
}
function readFromTopDown(rect, higest) {
var coded = [];
for(var i = 0; i < higest; i++){
var textMain = "";
rect.forEach(re => {
textMain += re.substring(i, i+1);
});
coded.push(textMain);
}
return coded;
}
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks"></p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle"></p>
</div>
Try and see

Make calculation based on information provided

I am building a website and I want to do calculations based on information provided. I obviously need to have information provided in two out of the three fields to calculate the third's value.
The three fields are:
Price Per Gallon
Gallons Bought
Total Sale
I obviously know that I can calculate the amount of gas bought by dividing the Total Sale amount by the Price Per Gallon.
However I want to calculate based on whatever two fields are entered. I am trying to find out the best way to do this.
I know this much:
Check to see which fields are empty
Determine which type of calculation to make
Here is what I have so far:
<form>
<input type="number" id="totalSale" placeholder="Total Sale Amount" class="calculate" />
<input type="number" id="gallonPrice" placeholder="Price Per Gallon" class="calculate" />
<input type="number" id="gallons" placeholder="Gallons" class="calculate" />
</form>
<script>
var e = document.getElementsByClassName("calculate");
function calc(){
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
if (sale_amt || ppg !== null) {
var calc_gallons = sale_amt.value / ppg.value;
gallons.value = calc_gallons.toFixed(3);
}
}
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
}
</script>
the logic should take into consideration which element is currently being entered (that will be this in calc). Also, you need to take into consideration what happens when all three have values, and you change one ... which of the other two should be changed?
See if this works for you
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
function calc(){
var els = [sale_amt, ppg, gallons];
var values = [sale_amt.value, ppg.value, gallons.value];
var disabledElement = els.find(e=>e.disabled);
var numValues = els.filter(e => e.value !== '' && !e.disabled).length;
var calc_gallons = function() {
gallons.value = (values[0] / values[1]).toFixed(3);
};
var calc_ppg = function() {
ppg.value = (values[0] / values[2]).toFixed(3);
};
var calc_sale = function() {
sale_amt.value = (values[1] * values[2]).toFixed(2);
};
if (numValues < 3) {
if (numValues == 1 && disabledElement) {
disabledElement.disabled = false;
disabledElement.value = '';
disabledElement = null;
}
els.forEach(e => e.disabled = e == disabledElement || (numValues == 2 && e.value === ''));
}
disabledElement = els.find(e=>e.disabled);
switch((disabledElement && disabledElement.id) || '') {
case 'totalSale':
calc_sale();
break;
case 'gallonPrice':
calc_ppg();
break;
case 'gallons':
calc_gallons();
break;
}
}
var e = document.getElementsByClassName("calculate");
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
e[i].addEventListener('change', calc, false);
}

Improving Secure Password Generator

Simple Password Generator Example:
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOP" +
"1234567890" +
"#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/",
pass = "",
PL = 10;
for (var x = 0; x < PL; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword();
}
<form name="myform" method="post" action="">
<table width="100%" border="0">
<tr>
<td>Password:</td>
<td>
<input name="row_password" type="text" size="40">
<input type="button" class="button" value="Generate" onClick="generate();" tabindex="2">
</td>
</tr>
</table>
</form>
Improving Functionality Questions
1). Obtaining All Values Within Variable
Taking the base script above, how can I call chars.length and chars.charAt(i) where chars equals all the values within Chars?
var Chars = {};
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
2). Implementing a checkbox system for less advanced password
To generate a less advanced password, such as not including symbox via unchecking a checkbox, how can I make it so only Chars.abc, Chars.ABE, and Chars.Num values are used?
3). Equally Divide Password Length By Chars
Round down (Password length / Chars used ), ie; the example used in this question generates a 10 character password and uses all charecters, therefore there would be a minimum of 2 of each Chars.
The 3rd functionality is missing and will probably be way more sophisticated. But this is a simple solution to the 1st and 2nd ones.
var output = document.getElementsByTagName('output')[0];
var Chars = {};
Chars.length = 16;
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.NumRequired = true;
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
var generator = new randomPasswordGenerator(Chars);
var simpleGenerator = new randomPasswordGenerator({
length: 6,
abc: 'abc',
Num: '0'
});
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', clickFunction);
var checkbox = document.getElementsByTagName('input')[0];
function clickFunction () {
if (checkbox.checked) output.textContent = simpleGenerator.randomPassword();
else output.textContent = generator.randomPassword();
}
function randomPasswordGenerator(opts) {
for(var p in opts) this[p] = opts[p];
this.randomPassword = randomPassword;
}
function randomPassword() {
var chars = (this.abc || "") +
(this.ABE || "") +
(this.Num || "") +
(this.Sym || ""),
pass = [],
PL = this.length;
if (this.NumRequired) {
var r = Math.floor(Math.random() * this.Num.length);
var i = Math.floor(Math.random() * PL);
pass[i] = this.Num[r];
}
for (var x = 0; x < PL; x++) {
if(!pass[x]) {
var i = Math.floor(Math.random() * chars.length);
pass[x] = chars.charAt(i);
}
}
return pass.join('');
}
output {
margin: 12px;
display: block;
border-bottom: 1px solid
}
<button>Generate</button>
<input type="checkbox">Simple
<output></output>

Unable to call function within jQuery

I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/

Categories

Resources