Javascript won't change page content - javascript

Had this code running fine when I was using a javascript window prompt to input the length. I have now changed it to use an if statement and a dropdown window in the html, and it does not seem to work? Been trying to figure out where the problem is for a few hours, so would be really grateful if someone could point me in the right direction!
HTML:
<select name="paraSize" id ="paraSize">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
JavaScript:
var getRekt = function() {
var ipsumLength = 0
var numberParagraph = document.getElementById("paragraphs").value;
var paragraphSize = document.getElementById("paraSize").value;
var startRektIpsum = document.getElementById("startRekt").checked;
if (paragraphSize === small) {
(ipsumLength = 9);
};
else if (paragraphSize === medium) {
(ipsumLength = 25);
};
else if (paragraphSize === large) {
(ipsumLength= 38);
};
var string = "Rekt Ipsum ";
var rektIpsum = [
//Array of words which I won't bore you with
];
for (i = 0; i <= ipsumLength; i++) {
(string = (string + " " + rektIpsum[Math.floor((Math.random() * (rektIpsum.length)) )]))
}
document.getElementById("p1").innerHTML = (string);
}

As noted in my comments the problems was syntactical... but the solution can be simplified to
var paragraphSizeMap = {
small: 9,
medium: 25,
large: 38
}
var getRekt = function () {
var numberParagraph = document.getElementById("paragraphs").value;
var paragraphSize = document.getElementById("paraSize").value;
var startRektIpsum = document.getElementById("startRekt").checked;
var ipsumLength = paragraphSizeMap[paragraphSize] || 0;
var string = "Rekt Ipsum ";
var rektIpsum = ['', '', ''];
for (i = 0; i < ipsumLength; i++) {
string += " " + rektIpsum[Math.floor(Math.random() * rektIpsum.length)]
}
document.getElementById("p1").innerHTML = string;
}

Related

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

Calculation does not return the correct value

can anyone tell me what is the error on this javascript code?
Program: http://utilizaweb.com.br/aposentadorianovo/
function calcula(){
var fieldsContainer=document.getElementsByClassName("trabalho")[0].
getElementsByClassName("row"),
i,
jobFields=[],
len,
newAge=0,
selfGender=document.aposentadoria.sexo.value,
workedDays=0,
workedMonthies=0,
workedYears=0;
len=fieldsContainer.length;
for(i=0;len>i;i++){
jobFields[i]={
admissionDate:new Date(fieldsContainer[i].getElementsByClassName("admissao-area")[0].children[1].value),//data de admissão,
ageRule:fieldsContainer[i].getElementsByClassName("regra-area")[0].children[0].value,//regra
demissionDate:new Date(fieldsContainer[i].getElementsByClassName("demissao-area")[0].children[1].value),//data de demissão
jobBusiness:fieldsContainer[i].getElementsByClassName("empresa-area")[0].children[1].value//empresa do trabalho
};
if (jobFields[i].demissionDate > jobFields[i].admissionDate) {
jobFields[i].workedYears=jobFields[i].demissionDate.getFullYear() - jobFields[i].admissionDate.getFullYear();
jobFields[i].workedMonthies=jobFields[i].demissionDate.getMonth() - jobFields[i].admissionDate.getMonth();
jobFields[i].workedDays=jobFields[i].demissionDate.getDate() - jobFields[i].admissionDate.getDate();
alert(jobFields[i].workedYears)
} else {
alert("A data de admissão deve ser anterior à data de demissão.");
throw new Error("Conversor :: Admission date must be older than demission date.")
}
}
var fieldsRule=[];
len=jobFields.length;
for(i=0;len>i;i++){
fieldsRule[i]=jobFields[i].ageRule
}
var calculateFields=[],
higherRule=Math.max.apply(fieldsRule)
len=jobFields.length;
for(i=0;len>i;i++){
if(fieldsRule[i]===higherRule){
calculateFields[i]=i
}
}
var ageMultiplyBy,
missingYears,
jobYearsEnd;
len=calculateFields.length;
if (selfGender === "M") {
for(i=0;len>i;i++){
ageMultiplyBy=
jobFields[calculateFields[i]].ageRule==="25"?1.40:
jobFields[calculateFields[i]].ageRule==="20"?1.75:
jobFields[calculateFields[i]].ageRule==="15"?2.33:
1.75;
newAge=jobFields[calculateFields[i]].workedYears*ageMultiplyBy;
missingYears=newAge - 35
}
} else {
for(i=0;len>i;i++){
ageMultiplyBy=
jobFields[calculateFields[i]].ageRule==="25"?1.20:
jobFields[calculateFields[i]].ageRule==="20"?1.50:
jobFields[calculateFields[i]].ageRule==="15"?2:
1.20;
newAge=jobFields[calculateFields[i]].workedYears*ageMultiplyBy;
missingYears=newAge - 30
}
}
alert(missingYears)
if (missingYears < 0) {
jobYearsEnd=missingYears * -1;
}
document.getElementById("anosTrabalhados").innerHTML = workedYears+ " anos";
document.getElementById("result").innerHTML = "<img src='./img/aviso.png'>" +"Você trabalhou " +workedYears+ " anos, " +workedMonthies+ " meses e " +workedDays+ " dias"+ "<br />" +"Faltam " +jobYearsEnd+ " anos para se aposentar"
}
[IF WASN'T WELL EXPLAINED, PLEASE TELL ME. I DONT SPEAK ENGLISH SO WELL]
I need get the value of the admissionDate and of the demissionDate and subtract of each line, including those added by the user. Then, I need get the biggest values of rules are equal, and add up the time worked in each one. Then, the program takes the time worked added up and multiply by the value of each rule and subtract of 35 in case of male and of 30 in case of female. And then displays the value calculated last (minus 30 or 35).
Where the code is wrong?
Look the code by View Source
I did what I could with this one as there are several challenges and a couple of points where I am not 100 percent sure your intent. I believe you can work from here. Date stuff is hard when you work with multiple related dates. What if the boundary crosses daylight savings time etc. To assist with that I used a date library, feel free to get another or use it, I pasted it into the fiddle code; use it or get another that does that stuff rather than re-invent one. I did not use it extensively.
Here is a saved fiddle to test/try it out: (see the bottom for the good parts) https://jsfiddle.net/MarkSchultheiss/1ttmecoe/
Link the the date library: http://slingfive.com/pages/code/jsDate/jsDate.html
Explanation:
First off, your undisclosed code replicates an ID and those MUST be unique, and when you use that it is in error. I fixed that by using jQuery .clone() I also put a method to add/remove rows (all but last one) from your list) which was lacking on your page.
Code snip:
document.getElementById("anosTrabalhados").innerHTML
I will show you how to fix that (see the markup and .clone())
You have some rather complex selectors which can be simplified by the use of classes.
Code snip:
jobFields[i]={
admissionDate:new Date(fieldsContainer[i].getElementsByClassName("admissao-area")[0].children[1].value),//data de admissão,
revised:
var thisRow = fieldsContainer[i];
jobFields[i] = {
admissionDate: new Date(thisRow.getElementsByClassName("dataAdmissao")[0].value),
Checking/validation of dates right in the middle of a loop, perhaps you might check those before you loop? I left that for now as it was.
Code snip:
if (jobFields[i].demissionDate > jobFields[i].admissionDate) {
This appears to be a syntax issue here:
higherRule=Math.max.apply(fieldsRule) //old
higherRule=Math.max.apply(null, fieldsRule); //repaired
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
Remove constants from code and put them in an object:
Code snip:
var calcVals = {
rules: {
male: {
sex: "M",
defaultRate: 1.75,
ageVar: 35,
ageRules: [{
age: "25",
val: 1.40
}, {
age: "20",
val: 1.75
}, {
age: "15",
val: 2.33
}]
},
female: {
sex: "M",
defaultRate: 1.50,
ageVar: 30,
ageRules: [{
age: "25",
val: 1.20
}, {
age: "20",
val: 1.50
}, {
age: "15",
val: 2.00
}]
}
}
};
then use it later: (this gets rid of the duplicate hard coded conditional making it simpler and more maintainable)
calcT = (selfGender === "M") ? calcT = calcVals.rules.male : calcT = calcVals.rules.female;
ageMultiplyBy = calcT.defaultRate;
for (i = 0; len > i; i++) {
for (var j = 0; j < calcT.ageRules.length; j++) {
if (jobFields[calculateFields[i]].ageRule === calcT.ageRules[j].age) {
ageMultiplyBy = calcT.ageRules[j].val;
break;
}
}
...more code
Assignment of a string to an array
Code snip:
fieldsRule[i]=jobFields[i].ageRule
This changes this comparison: (see the next code segment as well)
if(fieldsRule[i]===higherRule){
The fieldsRule[i] is a string and higherRule is a numeric (see the Math.max.apply above)
You set the iteration variable len based on jobFields but access the fieldsRule[i] which MIGHT be undefined. Did you mean to push to the array rather than assign to it? I ask because later on you use len=calculateFields.length; as an iterate value. Note that all the fieldsRule[i] might not be evaluated if the lengths differ on the arrays OR it might have an undefined value. (note that this is where your desired functionality becomes less clear)
len=jobFields.length;
for(i=0;len>i;i++){
if(fieldsRule[i]===higherRule){
calculateFields[i]=i
}
}
See this later down: newAge=jobFields[calculateFields[i]].workedYears*ageMultiplyBy; where calculateFields[i] might be undefined.
Revised markup:
<form class="form-calculadora" name="aposentadoria">
<fieldset class="sexo">
<legend>Sexo</legend>
<select id="sexo" class="text-area">
<option value="M">Masculino</option>
<option value="F">Feminino</option>
</select>
</fieldset>
<fieldset class="trabalho">
<div class="row p_scents">
<div class="empresa-area">
<p class="title">Empresa</p>
<input type="text" class="text-area empresa" placeholder="Empresa: ">
</div>
<div class="regra-area">
<p class="title">Regra</p>
<select class="text-area regra">
<option value="25">25 anos</option>
<option value="20">20 anos</option>
<option value="15">15 anos</option>
</select>
</div>
<div class="admissao-area">
<p class="title">Admissão</p>
<input type="date" class="text-area dataAdmissao" placeholder="Admissão: " />
</div>
<div class="demissao-area">
<p class="title">Demissão</p>
<input type="date" class="text-area dataDemissao" placeholder="Demissão: " />
</div>
<div class="anos-area">
<p class="anosTrabalhados">0 anos</p>
</div>
<button class="removerow">
Remove Row
</button>
</div>
</fieldset>
<p class="add-empresa"><i class="fa fa-user-plus"></i> Adicionar Empresa</p>
<p id="result">Você trabalhou 0 anos, 0 meses e 0 dias
<br/>Faltam undefined anos para se aposentar</p>
<input type="button" value="Calcular" class="btn" id="calcular" />
</form>
Revised code:
var calcVals = {
rules: {
male: {
sex: "M",
defaultRate: 1.75,
ageVar: 35,
ageRules: [{
age: "25",
val: 1.40
}, {
age: "20",
val: 1.75
}, {
age: "15",
val: 2.33
}]
},
female: {
sex: "M",
defaultRate: 1.50,
ageVar: 30,
ageRules: [{
age: "25",
val: 1.20
}, {
age: "20",
val: 1.50
}, {
age: "15",
val: 2.00
}]
}
}
};
function calcula() {
var rows = $('.row');
var fieldsContainer = document.getElementsByClassName("trabalho")[0].
getElementsByClassName("row"),
i,
jobFields = [],
len,
newAge = 0,
selfGender = document.aposentadoria.sexo.value,
workedDays = 0,
workedMonthies = 0,
workedYears = 0;
var fieldsRule = [];
var calculateFields = [],
len = fieldsContainer.length;
for (i = 0; i < len; i++) {
var thisRow = fieldsContainer[i];
jobFields[i] = {
admissionDate: new Date(thisRow.getElementsByClassName("dataAdmissao")[0].value),
demissionDate: new Date(thisRow.getElementsByClassName("dataDemissao")[0].value),
ageRule: thisRow.getElementsByClassName("regra")[0].value,
jobBusiness: thisRow.getElementsByClassName("empresa")[0].value
};
// console.dir(jobFields);
if (jobFields[i].demissionDate > jobFields[i].admissionDate) {
jobFields[i].workedYears = Date.DateDiff('yyyy', jobFields[i].admissionDate, jobFields[i].demissionDate);
// get months after remove years
jobFields[i].workedMonthies = Date.DateDiff('m', jobFields[i].admissionDate, jobFields[i].demissionDate) - (jobFields[i].workedYears * 12);
// console.log('days:' + Date.DateDiff('d', jobFields[i].admissionDate, jobFields[i].demissionDate) );
// get days worked after remove years/months
var adate = new Date(jobFields[i].demissionDate);
adate = new Date(adate.setFullYear(jobFields[i].demissionDate.getFullYear() - jobFields[i].workedYears));
adate = new Date(adate.setMonth((adate.getMonth()) - jobFields[i].workedMonthies));
jobFields[i].workedDays = Date.DateDiff('d', jobFields[i].admissionDate, adate); //- (new Date(jobFields[i].admissionDate) - new Date(jobFields[i].demissionDate));
// console.log('worked' + i + ":" + jobFields[i].workedYears);
} else {
alert("A data de admissão deve ser anterior à data de demissão. not less");
// throw new Error("Conversor :: Admission date must be older than demission date.")
}
}
len = jobFields.length;
for (i = 0; len > i; i++) {
fieldsRule[i] = +jobFields[i].ageRule;
}
var higherRule = Math.max.apply(null, fieldsRule);
console.log("higherRule:" + higherRule + " fLen:" + fieldsRule.length);
len = jobFields.length;
console.dir({
"jobf": jobFields
});
//console.dir(fieldsRule);
for (i = 0; i < len; i++) {
if (fieldsRule[i] === higherRule) {
calculateFields[i] = i;
}
}
console.dir({
"calcf": calculateFields
});
var ageMultiplyBy,
missingYears,
jobYearsEnd;
console.dir(fieldsRule);
len = calculateFields.length;
var calcT = {};
calcT = (selfGender === "M") ? calcT = calcVals.rules.male : calcT = calcVals.rules.female;
ageMultiplyBy = calcT.defaultRate;
for (i = 0; len > i; i++) {
for (var j = 0; j < calcT.ageRules.length; j++) {
if (jobFields[calculateFields[i]].ageRule === calcT.ageRules[j].age) {
ageMultiplyBy = calcT.ageRules[j].val;
break;
}
}
newAge = jobFields[calculateFields[i]].workedYears * ageMultiplyBy;
missingYears = newAge - calcT.ageVar;
}
console.log('mys:' + missingYears);
if (missingYears < 0) {
jobYearsEnd = (+missingYears) * -1;
}
len = jobFields.length;
for (i = 0; i < len; i++) {
workedYears = workedYears + jobFields[i].workedYears;
workedMonthies = workedMonthies + jobFields[i].workedMonthies;
workedDays = workedDays + jobFields[i].workedDays;;
}
//invalid id cannot be dupe document.getElementById("anosTrabalhados").innerHTML = workedYears + " anos";
for (var m = 0; m < rows.length; m++) {
console.log('wy:' + workedYears);
$('.row').eq(m).find('.anosTrabalhados').text(workedYears + " anos");
}
// document.getElementById("anosTrabalhados").innerHTML = workedYears + " anos";
document.getElementById("result").innerHTML = "<img src='./img/aviso.png'>" + "Você trabalhou " + workedYears + " anos, " + workedMonthies + " meses e " + workedDays + " dias" + "<br />" + "Faltam " + jobYearsEnd + " anos para se aposentar"
}
$(function() {
// set defaults for testing
makedefaults(0);
$('#calcular').on('click', function() {
calcula();
});
// add a row
$('#addScnt').on('click', function(e) {
var rowContainer = $('.trabalho');
var rows = rowContainer.find('.row');
var newRow = rows.eq(0).clone(true);
rowContainer.append(newRow);
e.preventDefault();
return false;
});
// remove any row but last one
$('.trabalho').on('click', '.removerow', function(e) {
var rowsCount = $('.trabalho').find('.row').length;
if (rowsCount > 1) {
$(this).parents('.row').remove();
}
e.preventDefault();
return false;
});
});

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/

My generated french word duplicates? When it shouldn't be

I've sorted this but now it's came back on... I've tried changing the for loops but it still seems to generate duplicate French words. It's suppose to not show the french word twice in the application run.
My jsFiddle is an exact replica:
http://jsfiddle.net/jamesw1/w8p7b6p3/17/
Javascript:
//James Wainwright's Mobile Apps Assignment
//Arrays of french and english words.
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers and make sure they aren't the same as each other.
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu using for loop. This loop runs once (on document load)
document.getElementById('generatedWord').textContent = foreignWords[number];
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Output the previous.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Declare variables 'outside' the onclick function so it ensures they work correctly.
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
var counter = 0;
var outputted = '';
//Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
var guessedList = new Array(6);
var correctList = new Array(6);
var wordGenerated = new Array(6);
//On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
document.getElementById('submitAns').onclick = function () {
//Declare variables for function.
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
//Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Generate a word here. ( call wordGen() )
wordGen();
//Create dynamic select menu for options they have to choose from.
document.getElementById('generatedWord').textContent = foreignWords[number];
//Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Outputting to the html page.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
//Count number of guesses
numGuesses++;
//Counter for placing guessed, correct and foreign word into there arrays.
counter++;
wordGenerated[counter] = foreignWords[number];
guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
correctList[counter] = translate[number];
//Once the application has finished...It will produce the following output.
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
outputted = "<table>";
for(var d=1;d<wordGenerated.length;d++){
outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td> <td>Guessed Word: " + guessedList[d] + "</td> <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
}
outputted += "</table>";
outputted += "<style type='text/css'>#hint{ display:none; }</style>";
//Output it to the html page.
document.getElementById('details').innerHTML = outputted;
}
};
document.getElementById('hint').onclick = function () {
alert(correctAns.charAt(0));
};
Html:
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="header">
<h1>James' Translation Guessing Game</h1>
</div>
<div data-role="content" class="main">
<h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />
<!-- What question we're upto -->
<h2 id="numGuess">Question #</h2 >
<!-- The generated French Word Aswell as end of app details-->
<div align="center" class="frenchWord" style="position:">
<!--Generated french word details-->
<div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center" id="generatedWord"></div>
<br />
<br />
<!-- Show the user there guessed answers, correct and foreign word -->
<div id="details"></div>
</div>
<!-- Select menu output -->
<div align="center" id="output"></div>
<img id="hintImg" style="" src="images/hint.png" alt="Hint" />
<!-- Buttons, Call Functions -->
<button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
<input type="button" value="New Game" onClick="document.location.reload(true)">
<script>
//Simple animation
$(document).ready(function(){
$("#generatedWord").animate({
opacity: 0.8,
margin: "40px 0px 100px 0px",
width: "20%",
padding: "30px",
}, 1500 );
});
</script>
</div>
<div data-role="footer">
<h4>James Wainwright</h4>
</div>
</div>
This might do it. Before assigning a number to the RanNumbers array I delete it from the original RanNumbers array to prevent duplication. It might make more sense to just maintain a separate array of numbers to be used in the questions but I tried to change as little as possible.
Updated Fiddle
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * RanNumbers.length);
while(temp==correctAns){
temp = Math.floor(Math.random() * RanNumbers.length);
delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}

Drop down box text disappears after completing a function, how can I get it to display what option was chosen?

The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}

Categories

Resources