This is the code I currently have. I am having issues displaying the ordinals as I am not sure what for loop to put then in. Can someone please assist?
var bandsString = "";
var newBandString = "";
var bandsListArray = ["Linkin Park", "Atmosphere", "Rage Against The Machine", "Immortal Technique", "System of a Down"];
for (var i = 0; i < bandsListArray.length; i++) {
var currentBand = bandsListArray[i];
bandsString += "<li> My #" + [i + 1] + " band is " + currentBand + "</li>";
}
var bands = i;
if (bands == 0) {
bands = i + "st";;
} else if (bands == 1) {
bands = i + "nd";
} else if (bands == 2) {
bands = i + "rd";
} else if (bands == 3) {
bands = i + "th";
} else if (bands == 4) {
bands = i + "th";
} else {
}
for (var i = 0; i < bandsListArray.length; i++) {
var newBandList = bandsListArray[i];
newBandString += "<li>My # " + [i + 1] + " band is " + currentBand + "</li>";
}
document.write(bandsString);
document.write(newBandString);
I'm not exactly sure what you're trying to do, but does this help? Instead of manually working out how to put the correct ordinal suffix ('st', 'nd', 'rd', etc.) on the numbers, I googled a function.
The ordinal_suffix_of function works like this:
This first part is the start of the function. Hopefully this is self-explanatory. We're creating a function that accepts one parameter, that will be named i inside the function.
function ordinal_suffix_of(i) {
This next part defines j and k. You can declare multiple variables while only typing var once by using commas, as this code does:
var j = i % 10,
k = i % 100;
This would do exactly the same thing:
var j = i % 10;
var k = i % 100;
The percent sign (%) is called "modulus" and is a mathematical operator. What it does is divide the left operand by the right operand and returns the remainder. So in the case of j, it's being assigned remainder of dividing i by 10. If i was 14, for example, j would be 4. If i was 179, j would be 9. The same thing happens for k except that it's divided by 100 instead of 10.
What it's effectively doing is extracting the last 1 digit (for j) and the last 2 digits (for k) and then just checking (in the if statements) what ordinal suffixes they should have.
The reason for k is that you always want numbers ending in 1, 2, or 3 to have the suffixes st, nd , and rd except when the number ends in 11, 12, or 13, in which case it should get the suffix th. So for example, 112 should be 112th, and 313513 should be 313513th. k handles this by making it so that if the number ends in 11, 12, or 13 we only add th. Note that 11 % 100 will result in 11, so this works for 11, 12, and 13 as well.
var bandsString = "";
var newBandString = "";
var bandsListArray = ["Linkin Park", "Atmosphere", "Rage Against The Machine", "Immortal Technique", "System of a Down"];
for (var i = 0; i < bandsListArray.length; i++) {
var currentBand = bandsListArray[i];
bandsString += "<li> My #" + (i + 1) + " band is " + currentBand + "</li>";
}
for (var i = 0; i < bandsListArray.length; i++) {
var newBandList = bandsListArray[i];
newBandString += "<li>My " + ordinal_suffix_of(i + 1) + " band is " + newBandList + "</li>";
}
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
document.write(bandsString);
document.write(newBandString);
Try this, just make the code more simple
var bandsString = "";
var newBandString = "";
var bandsListArray = ["Linkin Park", "Atmosphere", "Rage Against The Machine", "Immortal Technique", "System of a Down"];
for (var i = 0; i < bandsListArray.length; i++) {
var currentBand = bandsListArray[i];
bandsString += "<li> My #" + [i + 1] + " band is " + currentBand + "</li>";
newBandString += "<li> My #" + numeric(i+1) + " band is " + currentBand + "</li>";
}
function numeric(i){
var bands = i+"th";
if (i == 1) {
bands = i + "st";;
} else if (i == 2) {
bands = i + "nd";
} else if (i == 3) {
bands = i + "rd";
}
return bands;
}
document.write(bandsString);
document.write(newBandString);
If this is what you are trying to achieve is:
My 2nd band is Atmosphere
Then this how you might achieve it
var bandsString = "";
var newBandString = "";
var bandsListArray = ["Linkin Park", "Atmosphere", "Rage Against The Machine", "Immortal Technique", "System of a Down"];
for (var i = 0; i < bandsListArray.length; i++) {
var currentBand = bandsListArray[i];
bandsString += "<li> My #" + (i + 1) + " band is " + currentBand + "</li>";
newBandString += "<li>My " + numberSuffix(i + 1) + " band is " + currentBand + "</li>";
}
function numberSuffix(number){
if(number % 10==1) return number+'st';
if(number % 10==2) return number+'nd';
if(number % 10==3) return number+'rd';
return number+'th';
}
document.write(bandsString);
document.write(newBandString);
Related
I want to console.log a string but also add numbers inside of it. For example if I use the following code:
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log("#" + i + 1 + " Heads");
} else {
console.log("#" + i + 1 + " Tails");
}
}
Since what I want to console.log starts with a string I can't seem to add numbers right after it. They become strings.
I want to get:
"#2 Tails"
But I get:
"#11 Tails"
How do I get "#2 Tails" instead of "#11 Tails"?
You need to wrap your addition in brackets.
console.log("#" + (i + 1) + " Heads");
or use string interpolation
console.log(`#${i+1} Heads`);
You can first sum up the value of i and 1 to num before the concatination
1)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
const num = i + 1;
if (coinFlip === 1) {
console.log("#" + num + " Heads");
} else {
console.log("#" + num + " Tails");
}
}
2)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log("#" + (i + 1) + " Heads");
} else {
console.log("#" + (i + 1) + " Tails");
}
}
3)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log(`#${i + 1} Heads`);
} else {
console.log(`#${i + 1} Tails`);
}
}
In my table 1st column has a tags with href's and 3rd column has some text. So, I want to save all href's into an array where their respective 3rd column matches some string and use it for later purpose. I had tried the following code nothing seems wrong to me, can some one assist me with this.
function findimagelinks(){
var rows = jQuery(".sortable tr.even").length + jQuery(".sortable tr.odd").length;
var imglinks = [];
for (i=0; i<rows; i++){
var conditionvalue =jQuery(".sortable tr:eq(i+1) td:eq(3)").text();
if(conditionvalue == "some string"){
imglinks[i] = jQuery(".sortable tr:eq(i+1) td:eq(0) a").attr('href');
}
}
console.log(imglinks);
}
findimagelinks();
String concatenation is not right!
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
// ------------------------------------------^
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
// -----------------------------------^
Updated Snippet
function findimagelinks(){
var rows = jQuery(".sortable tr.even").length + jQuery(".sortable tr.odd").length;
var imglinks = [];
for (i = 0; i < rows; i++) {
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
if (conditionvalue == "some string") {
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
}
}
console.log(imglinks);
}
findimagelinks();
Your selector is wrong. Properly concatenate the strings like this
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
Then your code will look like,
for (i = 0; i < rows; i++) {
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
if (conditionvalue == "some string") {
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
}
}
Basically I have 5 words picked out of an array (English Words) And I pick 1 French word out of another array which the user then has to guess what that french word means in english.
At the moment I am adding the Correct English Answer to the end of the select menu because I don't know how to add it inbetween the others randomly, or more so to shuffle the select menus options
I Have added my JSfiddle below, It is an exact replica. You will realise that the bottom option is always correct! (The user will begin to know the pattern). I've also had to add my javascript below to be able to post the JSfiddle
http://jsfiddle.net/jamesw1/w8p7b6p3/5/
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 to pick the available answers
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 0; i < 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
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;
}
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
//On click, gather correct and wrong answers, create new numbers, create new options, create new word.
document.getElementById('submitAns').onclick = function () {
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
//Re doing the function, getting new values...
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i <= 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
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.
numGuesses++;
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();
}
};
You should use Math.random method, it would be something like this:
var correctAnswerIndex = Math.floor(Math.random() * 7); //gives random number between 0-6
for (var i = 1; i <= 6; i++) {
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
you will need just to adjust else statement, as RanNumbers may not have 6 items. So maybe to introduce additional counter that would be used insead of i. (something like translate[RanNumbers[counter++]])
How do I do an If statement within the below for loop after "holmesminutes" variable reaches a certain amount e.g. 60 and then once it reaches 60 it skips one of the array items. So for example after 60 minutes the loop should be on Peacock in terms of the array items but I want it to skip it by one and put "Scarlett" for 60 minutes. I then need to do this again after 100 minutes.
document.write('<table id="myTable1" border="1" cellspacing="1" cellpadding="5">');
var clients = new Array("Mustard","Plum","Green","Peacock","Scarlett","White");
var indexCounter,
holmesminutes =0,
tableId1 =0;
for (var repeatCounter = 0;
repeatCounter < 5 && holmesminutes < 315; repeatCounter++)
{
for (indexCounter = 0; holmesminutes < 315; indexCounter++)
{
document.write("<tr>");
tableId1 = tableId1 + 1;
document.write('<td id="' + tableId1 + '">'
+ clients[indexCounter] + '</td>');
document.write("<td> Holmes </td>");
holmesminutes = holmesminutes + 15;
document.write("<td>" + holmesminutes + "</td> </tr>");
}
}
document.write("</table> <br>");
It's much simpler to understand your code if your control variable is holmesminutes.
If you need to skip once after 100, just skip when it's 105.
indexCounter = 0;
MAX_CLIENTS = clients.length;
for (var holmesminutes = 0; holmesminutes < 315; holmesminutes += 15)
{
if (holmesminutes != 60 && holmesminutes != 105) {
tableId1 = tableId1 + 1;
document.write("<tr>");
document.write('<td id="' + tableId1 + '">' +
clients[indexCounter] + '</td>');
document.write("<td> Holmes </td>");
document.write("<td>" + holmesminutes + "</td> </tr>");
}
indexCounter += 1;
if (indexCounter == MAX_CLIENTS) indexCounter = 0;
}
I'm not sure if you want to exit when all clients are displayed or want to start over. If you want to exit just change to if (indexCounter == MAX_CLIENTS) break;
use breaks like this this;
<script>
var counter = 0, full_breakpoint = 15, inner_break = 8;
for(var a = 0; a<10; ++a){
for(var b = 0; b<10; ++b){
counter++;
if(counter >= full_breakpoint) {
console.log("full_breakpoint in <b>loop = " + counter);
break;
}else if(counter == inner_break){
console.log("inner_break in <b>loop = " + counter);
break;
}else console.log("no break = " + counter);
}
if(counter >= full_breakpoint){
console.log("outter <a> forloop at break_point = " + counter);
break;
}
}
console.log("finish " + counter);
</script>
Output;
no break = 1 javascript.html:16
no break = 2 javascript.html:16
no break = 3 javascript.html:16
no break = 4 javascript.html:16
no break = 5 javascript.html:16
no break = 6 javascript.html:16
no break = 7 javascript.html:16
inner_break in <b>loop = 8 javascript.html:14
no break = 9 javascript.html:16
no break = 10 javascript.html:16
no break = 11 javascript.html:16
no break = 12 javascript.html:16
no break = 13 javascript.html:16
no break = 14 javascript.html:16
full_breakpoint in <b>loop = 15 javascript.html:11
outter <a> forloop at break_point = 15 javascript.html:22
finish 15
To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.