Randomising array from a matrix (bidimensional array) - javascript

I Currently have the following matrix
const fileName = [
["a01", "b01", "c01", "d01", "e01", "f01", "g01", "h01", "i01", "j01", "k01", "l01"],
["a02", "b02", "c02", "d02", "e02", "f02", "g02", "h02", "i02", "j02", "k02", "l02"],
["a03", "b03", "c03", "d03", "e03", "f03", "g03", "h03", "i03", "j03", "k03", "l03"],
["a04", "b04", "c04", "d04", "e04", "f04", "g04", "h04", "i04", "j04", "k04", "l04"],
["a05", "b05", "c05", "d05", "e05", "f05", "g05", "h05", "i05", "j05", "k05", "l05"],
["a06", "b06", "c06", "d06", "e06", "f06", "g06", "h06", "i06", "j06", "k06", "l06"],
["a07", "b07", "c07", "d07", "e07", "f07", "g07", "h07", "i07", "j07", "k07", "l07"],
["a08", "b08", "c08", "d08", "e08", "f08", "g08", "h08", "i08", "j08", "k08", "l08"],
["a09", "b09", "c09", "d09", "e09", "f09", "g09", "h09", "i09", "j09", "k09", "l09"],
["a10", "b10", "c10", "d10", "e10", "f10", "g10", "h10", "i10", "j10", "k10", "l10"],
["a11", "b11", "c11", "d11", "e11", "f11", "g11", "h11", "i11", "j11", "k11", "l11"],
["a12", "b12", "c12", "d12", "e12", "f12", "g12", "h12", "i12", "j12", "k12", "l12"]
];
and I create a new array with filenames from it randomising 1 item of each subarray using this function:
function randomise() {
let sequence = fileName.map(option => {
const random = Math.floor(Math.random() * 11);
return option[random];
});
let randomSelection = sequence.map(createURL);
function createURL(fileName) {
return `assets/music/${fileName}.mp3`;
}
console.log(randomSelection);
}
So I get an array such as:
["assets/music/f01.mp3", "assets/music/f02.mp3", "assets/music/b03.mp3", "assets/music/k04.mp3", "assets/music/b05.mp3", "assets/music/f06.mp3", "assets/music/i07.mp3", "assets/music/d08.mp3", "assets/music/d09.mp3", "assets/music/g10.mp3", "assets/music/a11.mp3", "assets/music/d12.mp3"]
But I want to rearrange my matrix in this way:
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
I need to randomly select 1 item from each of the indexes of those subarrays, so one random item ending with "1", another ending with "2", etc
Could you help me please? Thanks!

If these are the actual values of the array you're using, you can just loop from 1 through 12 and stick it together with a random character from the string "abcdefghijk" using randojs' rando() function (or otherwise if you prefer).
for(var i = 1; i <= 12; i++){
console.log("assets/music/" + rando("abcdefghijk") + (i < 10 ? "0" : "") + i + ".mp3")
}
<script src="https://randojs.com/1.0.0.js"></script>
This code uses randojs.com to simplify the randomness and make it easier to read, so if you want to use this code, make sure this is in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
To answer the second part of your question (which you posted as another answer to this question), you don't need to keep your fileName variable to construct the HTML here if you'd rather not. You can do it like this instead:
var letters = "abcdefghijk";
for(var i = 0; i < letters.length; i++){
var musicRowID = letters.charAt(i) + "01";
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for(var j = 1; j <= 12; j++){
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`);
}
}

Very beautiful Aaron! I created the array like this:
let randomSelection = new Array();
function randomise() {
for (let i = 1; i <= 12; i++) {
let index = `assets/music/${rando("abcdefghijkl")}${i < 10 ? "0" : ""}${i}.mp3`;
randomSelection.push(index);
}
}
randomise()
The only problem now is that I was using the code below to populate a grid based in my fileName variable...
fileName.forEach(row => {
$("#music-grid").append(`<div id="music-row-${row.slice(0, 1)}" class="row no-gutters"></div>`);
row.forEach(col => {
$(`#music-row-${row.slice(0, 1)}`).append(
`<div class="col-1"><button id="${col}" class="btn bar song">${col.toUpperCase()}</button></div>`
);
});
});
Do you reckon it is better to keep my original fileName variable in order to allow it to populate the grid?
Thanks so much!

If I understood you correctly this will give you your desired output. Picking one letter for each number. Hope this helps for whatever you need it.
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
let pickedValues = [];
for (i = 0; i <= fileName.length; i++) {
let index = Math.floor(Math.random() * ((fileName.length - 1) - 0 + 1));
pickedValues[i] = (fileName[index][i]);
}
console.log(pickedValues);

Related

How can i get the length of a responsable URL in javascript

I need the length of the JSONOBJECT.routingpath.coordinates.length
i am getting the response with this url.
http://193.70.60.44:3000/taxi_server/api/v1.0/taxiroute
response from server ...
[{
"idtaxiroute": "3",
"routingpath": {
"type": "LineString",
"coordinates": [
[49.9670749, 7.8994591],
[49.9682897, 7.898872900000001],
[49.9682897, 7.898872900000001],
[49.9680662, 7.897596899999999],
[49.9680662, 7.897596899999999],
[49.9689168, 7.897404499999999],
[49.9689168, 7.897404499999999],
[49.9690376, 7.895451],
[49.9690376, 7.895451],
[49.9688003, 7.891565000000001],
[49.9688003, 7.891565000000001],
[49.966386, 7.888530899999999],
[49.966386, 7.888530899999999],
[49.9651325, 7.8884534],
[49.9651325, 7.8884534],
[49.9411728, 7.912222499999999],
[49.9411728, 7.912222499999999],
[49.9391022, 7.9152532],
[49.9391022, 7.9152532],
[49.9337381, 7.9157891],
[49.9337381, 7.9157891],
[49.9241653, 7.829844099999999],
[49.9241653, 7.829844099999999],
[49.9259564, 7.8275102],
[49.9259564, 7.8275102],
[49.922877, 7.8259417],
[49.922877, 7.8259417],
[49.92355939999999, 7.8055037],
[49.92355939999999, 7.8055037],
[49.9258713, 7.8004553],
[49.9258713, 7.8004553],
[49.9262293, 7.7978919],
[49.9262293, 7.7978919],
[49.92596469999999, 7.795387600000001],
[49.92596469999999, 7.795387600000001],
[49.9216437, 7.7577913],
[49.9216437, 7.7577913],
[49.91755209999999, 7.7473702],
[49.91755209999999, 7.7473702],
[49.9107566, 7.726173299999999],
[49.9107566, 7.726173299999999],
[49.9115306, 7.725327200000001]
]
},
"taxiid": 551,
"riderequestid": 7
}, {
"idtaxiroute": "4",
"routingpath": {
"type": "LineString",
"coordinates": [
[49.9670749, 7.8994591],
[49.9670378, 7.899477099999999],
[49.9670378, 7.899477099999999],
[49.9651449, 7.898171800000001],
[49.9651449, 7.898171800000001],
[49.9645179, 7.894035400000001],
[49.9645179, 7.894035400000001],
[49.9605222, 7.893961699999999],
[49.9605222, 7.893961699999999],
[49.95326799999999, 7.902490999999999],
[49.95326799999999, 7.902490999999999],
[49.9518747, 7.9065943],
[49.9518747, 7.9065943],
[49.9495675, 7.907795699999999],
[49.9495675, 7.907795699999999],
[49.9479066, 7.9125997],
[49.9479066, 7.9125997],
[49.9405005, 7.910934200000001],
[49.9405005, 7.910934200000001],
[49.9400513, 7.9114172]
]
},
"taxiid": 551,
"riderequestid": 7
}]
Code:
for(var i = 0; i < JSONOBJECT[i].routingpath.length; i++)
{
console.log("Type: " + JSONOBJECT[i].routingpath.coordinates[i][i]);
console.log("Types: " + i);
}
Can you help me?
It makes no sense to use JSONOBJECT[i] in the calculation of the limit of the for loop that uses i.
You need nested loops, one for the JSONOBJECT array, and an inner one for coordinates.
for (var i = 0; i < JSONOBJECT.length; i++) {
var coords = JSONOBJECT[i].routingpath.coordinates;
for (var j = 0; j < coords.length; j++) {
console.log("Type: " + coords[j]);
}
}

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;
});
});

Getting the value of "on" for radio buttons

var allQuestions = [{
question1: "What is 1 + 1?",
choices: ["1", "2", "3", 4],
correctAnswer: ["2"]
}, {
question2: "What is 2 + 2?",
choices: ["6", "2", "3", 4, ],
correctAnswer: ["4"]
}, {
question3: "What is 3 + 3?",
choices: ["3", "6", "9", 12],
correctAnswer: ["6"]
}];
var newArray = shuffleArray(allQuestions);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function appendQuestions(number) {
if (newArray == "undefined" || newArray == "null" || newArray.length == 0) {
document.getElementById("questionForm").innerHTML = "Complete!";
} else {
for (i = 0; i < 4; i++) {
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>")
}
}
}
$(function() {
$("#questionList").empty();
appendQuestions();
newArray.shift();
})
function isCorrectAnswer() {
checkedVal = $("input[type=radio][name=question]:checked").val();
if (checkedVal == newArray[0].correctAnswer) {
alert("Correct!");
} else {
alert("Wrong!");
}
alert(checkedVal);
}
$("#submitButton").click(function() {
isCorrectAnswer();
$("#questionForm").empty();
appendQuestions();
newArray.shift();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<section id='questions'>
<form id="questionForm">
</form>
<div style='clear:both'></div>
<input id='submitButton' type='button' value='Submit'>
</section>
</div>
First off, sorry for the amount of code pasted. I have no idea if I'm missing some small bug or if I'm just writing the wrong code, so I figured it would be best to post all of it.
I am trying to get the value of a radio button. In the isCorrectAnswer function the first 2 lines are to determine the value of the radio button that is currently checked. The problem is when I alert the value of the radio button, it just says "on". I have searched for the last hour trying to figure out what this means or how to fix it and could not find a thing.
I apologize if this is a stupid question or if it has already been answered.
You have to change this line :
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>");
To :
$("#questionForm").append("<input name='question' type='radio' value='" +
JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));
Hope this helps.

Output array to element classes

I'm trying to output a JSON object to different parts of an HTML page using the same classes.
I'm importing my JSON from an API but when I've put information into it (via input fields) it looks a little bit like this:
{
"trip": [
{ // the first object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "12:04"
},
"destination": {
"name": "Albany",
"time": "1:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "2:05"
},
"destination": {
"name": "Boston",
"time": "3:12"
}
}]
},
{ // the second object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "1:04"
},
"destination": {
"name": "Albany",
"time": "2:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "3:05"
},
"destination": {
"name": "Boston",
"time": "4:12"
}
}]
}]
}
I'm trying to display the information on my website, but I can't get it to behave the way I want it to.
The first time around I did it something like this (after fetching the JSON via my PHP-page):
function addDataToHTML(data){
var trips = data.trip;
$.each(trips, function(){
document.getElementById('show_all_results');
var summary = document.createElement('div');
summary.innerHTML = "<span class='origin_time'>" + this.leg[0].origin.time +
" </span><span class='origin_name'> " + this.leg[0].origin.name +
"</span><span>-</span><span class='destination_time'>" + this.leg[leg.length-1].destination.time +
" </span><span class='destination_name'> " + this.leg[this.leg.length-1].destination.name +
"</span>";
document.getElementById('show_all_results').appendChild(summary);
});
}
This works but the problem I'm having is that I want to add a button in the code which would give me more information via a display:block/none-functionality. The button (and the rest of the information) would be created similarly with me having to write it in the innerHTML part of the JS, but all the ways that I've tried haven't worked and I guess it's all about me creating the divs and other DOM objects in the JS code which means that the HTML doesn't really recognize them.
Anyhow, to get more control of the code I'm now trying something like this with the HTML:
<div id="show_all_results">
<div id='search_result_single'> // First results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
<div id='search_result_single'> // Second results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
...and so on.
</div>
The JS:
for (var i = 0; i < this.leg.length; i++) {
var originName = document.getElementsByClassName("origin_name");
var originTime = document.getElementsByClassName("origin_time");
var destTime = document.getElementsByClassName("destination_time");
var destName = document.getElementsByClassName("destination_name");
for (var x = 0; x < originName.length; x++) {
var originNameItem = originName[x];
originNameItem.innerHTML = this.leg[0].origin.name;
}
for (var y = 0; y < originTime.length; y++) {
var originTimeItem = originTime[y];
originTimeItem.innerHTML = this.leg[i].origin.time;
}
for (var z = 0; z < destTime.length; z++) {
var destTimeItem = destTime[z];
destTimeItem.innerHTML = this.leg[this.leg.length - 1].destination.time;
}
for (var a = 0; a < destName.length; a++) {
var destNameItem = destName[a];
destNameItem.innerHTML = this.leg[this.leg.length - 1].destination.name;
}
}
Is there anybody that can help me get each part of the leg-array into different parts of the page using the same classes as I've done? Or is there a better way?
This became really long, sorry about that, but please let me know if I can provide any additional information. Thanks!

Find element by data attributes that use "|" as separators

Fiddle Example
HTML markup:
<div data-id='23|24|25'></div>
<div data-id='29|30|31'></div>
Script:
var array = [
{
"mid": "24"
},
{
"mid": "26"
},
{
"mid": "28"
},
{
"mid": "29"
},
{
"mid": "30"
},
{
"mid": "31"
}
];
var item_html ="";
$.each(array,function(i,k) {
item_html = '<h3>'+k["mid"]+'</h3>';
$('div[data-id="'+k["mid"]+'"').append(item_html); ???????????
});
Would it be possible to find the div element if part of the "|" separated value in its data-id matches the mid?
I'm trying to get an output like this:
<div data-id='23|24|25'>
<h3>24</h3>
</div>
<div data-id='29|30|31'>
<h3>29</h3>
<h3>30</h3>
<h3>31</h3>
You should use the *= selector (contains):
$('div[data-id*="'+k["mid"]+'"').append(item_html);
The result you are looking for is something tricky. I have update your code. hope this will help you.
var array = [
{ "mid": "24"},
{"mid": "26"},
{"mid": "28"},
{"mid": "29"},
{"mid": "30"},
{"mid": "31"}
];
$('[data-id]').each(function(){
var $this = $(this), dataArr = $this.data('id').split('|'), i = 0;
for(;i< dataArr.length; i++) {
if(numInObjArr(array,dataArr[i])) {
$this.append('<h3>'+ dataArr[i] +'</h3>');
}
}
});
//function to check number in array object provided above
function numInObjArr(objArr, num){
for (var i = 0, len=objArr.length; i< len; i++){
if(objArr[i]["mid"] == num) {
return true;
}
}
return false;
}
http://jsfiddle.net/EZ56N/73/ to see the working example

Categories

Resources