giving buttons in an array an own ID - javascript

I need help for a project I am doing for school. We need to make a booking system for a cinema. To generate the chairs I made an array but how do I give each button an own ID?
This is my code:
function chair(){
for( i = 1 ; i <= 10; i = i + 1 ){
if ( i > 3 && i < 8 ){
document.write("<button>button</button>");
}else{
document.write("<button>hi</button>");
}
}
}

Well, you could do this:
document.write("<button id=btn" + i + ">button</button>");
Side notes:
You're falling prey to The Horror of Implicit Globals — declare your i variable.
Normally barring a reason to do something else, in programming we start with 0 rather than 1:
for (i = 0; i < 10; i = i + 1)
You don't have to, but that's the normal thing to do.
i = i + 1 can be written ++i ("increment i"):
for (i = 0; i < 10; ++i)
Again you don't have to, but that (or its cousin i++) would be much more common than i = i + 1.
document.write is fine for small class assignments and such, but just FWIW, you probably wouldn't want to use it in the real world. Use the DOM instead:
var btn = document.createElement("button");
btn.id = "btn" + i;
document.body.appendChild(btn);
HTH, as you're learning...

function chair()
{
var ID = 0;
for( i = 1 ; i <= 10; i = i + 1 )
{
if ( i > 3 && i < 8 ){
document.write("<button id=btn"+id+">button</button>");
} else{
document.write("<button id=btn"+id+">hi</button>");
}
id++;
}
}

var id=0;
for( i = 1 ; i <= 10; i = i + 1 )
{
if ( i > 3 && i < 8 )
{
document.write("<button id="+id+">button</button>");
id++;
}
else
{
document.write("<button id="+id+">hi</button>");
id++;
}
}

I would advise against document.write. You can do this
function chair() {
for (var i = 0; i < 10; i++) {
var btn = document.createElement("button");
btn.id = "btn" + i; // set the id
btn.innerHTML = (i > 3 && i < 8) ? "Button" : "hi";
document.body.appendChild(btn);
}
}
P.S I've updated the answer to meet T.J.Crowder's suggestions in his side notes.

Related

Slow execution of a loop in Apps Script

Basically what I am looking for is any recommendations you can provide me to make this piece of code to execute faster.
The intention of this piece of code its basically by testing some conditions obtain a score and the questions related for each profile selected, and print those scores in the "Results Sheet" and print the questions in Sheets assigned with the name of the profile.
Through some quick and basic testing I discovered whenever the loop starts to print either the results or the questions its where the slow execute starts.
Sorry for the mess on the code I just started programming in Apps
Script several weeks ago.
EDIT
To be quite more specific Im trying to find out if there is any work around to print the questions in the different sheets and values of the profiles. I took a look at the similar question and he addresses a loop using for..in, Im still trying to find out if there is any other logical process I can do to get those values.
var iGrade1 = 0;
var iGrade2 = 0.5;
var iGrade3 = 1;
var resultsSheet = SpreadsheetApp.getActive().getSheetByName('Results');
var iStartingColumn = 5;
var iCellD = 'D';
var iCellE = 'E';
var iTotCounter = 2;
var amountProfiles = profileSheet.getRange
(2, perfilSheet.getLastColumn()).getValue();
var iTotPerf = 0;
var iPT = 1;
var aResizeP = 1;
for( i = 2; i< questionsSheet.getLastRow() ; i++ ){
//Range
sBI = 'B' + i;
sDI = 'D' + i;
//Copies values like 1|2|3|4|, 3|4|, 2|3|, etc.
profileCodes = questionsSheet.getRange(sDI).getValue();
for(j = 0; j < amountProfiles; j++){
//There is a checkbox where user selects if he wants that profile or not
if(profileSheet.getRange(1,iStartingColumn).getValue()
=== 'Yes'){
var sheetProfile = SpreadsheetApp.getActive().getSheetByName
(profileSheet.getRange(3, iStartingColumn).getValue());
var totProfile = profileSheet.getRange(perfilSheet.getLastRow(), iStartingColumn).getValue();
//User can select in a checkbox between 'Bad' 'Regular' and 'Good'
if( ( questionsSheet.getRange( sBI ).getValue() === '× Bad' ) ){
if(profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade1; }
}
else if( ( questionsSheet.getRange( sBI ).getValue() === ' ± Regular' ) ){
if( profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade2; }
}
else if( ( questionsSheet.getRange( sBI ).getValue() === '✓ Good' ) ){
if(profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade3; }
}
if ( profileCodes.split('|').indexOf(String
(perfilSheet.getRange(2, iStartingColumn).getValue()))
> -1){
questionsSheet.getRange('A' + i + ':' + 'C' + i)
.copyTo(sheetProfile.getRange('A' + iPT),SpreadsheetApp
.CopyPasteType.PASTE_NORMAL,false);
sheetProfile.autoResizeColumn(aResizeP);
}
if(iTotPerf != 0){
resultadosSheet.getRange(iCellD + iTotCounter).setValue(resultadosSheet.getRange(iCellD + iTotCounter).getValue() + iTotPerf);
resultsSheet.getRange(iCellE + iTotCounter).setValue( ( (resultsSheet.getRange(iCellD + iTotCounter).getValue() * 100)/ totPerfil )/ 100);
}
}
iTotPerf = 0;
iTotCounter++;
iStartingColumn++;
}
iPT += 1;
iTotCounter = 2;
iStartingColumn = 5;
}

Javascript: Calculating Min/Max/Average

I wrote this code in my html site, in Javascript, but is not working right. Most times it seems to ignore some entries and just randomly selects which is the min/max value. Also, when I tried to calculate average values, I got a string instead of a number, even though the variable is declared as 0 in the beginning. e.g performing 0+1+1+2+3+5 = 011235 instead of 12.
Here is the code, thanks in advance.
**EDIT: I added the student average code in the end, but it doesn't work, it doesn't show any results on the page, not even the "student" + [i] part. On the other hand, the parseInt() command worked, and made everything work as it should, thank you :)
<script language = "javascript">
function myFunction() {
var course0 = [];
var course1 = [];
var course2 = [];
var minstugrade = 100;
var maxstugrade = 0;
var minstugradetext = "";
var maxstugradetext = "";
var stuavgarr = [];
var minstuavg = 100;
var maxstuavg = 0;
var minstuavgtext = "";
var maxstuavgtext = "";
var mincougrade = 100;
var maxcougrade = 0;
var mincougradetext = "";
var maxcougradetext = "";
var mincouavg = 100;
var maxcouavg = 0;
var mincouavgtext = "";
var maxcouavgtext = "";
var couavg = 0;
//add form items to array
var x = document.getElementById("course0");
var i;
for (i = 0; i < x.length ;i++) {
course0.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course1");
var i;
for (i = 0; i < x.length ;i++) {
course1.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course2");
var i;
for (i = 0; i < x.length ;i++) {
course2.push(parseInt(x.elements[i].value));
}
//calculate course & student min/max
for (i = 0; i < course0.length; i++) {
if (course0[i] < mincougrade) {
mincougrade = course0[i];
mincougradetext = "course0";
}
if (course0[i] > maxcougrade) {
maxcougrade = course0[i];
maxcougradetext = "course0";
}
if (course0[i] < minstugrade) {
minstugrade = course0[i];
minstugradetext = "student" + [i];
}
if (course0[i] > maxstugrade) {
maxstugrade = course0[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course1.length; i++) {
if (course1[i] < mincougrade) {
mincougrade = course1[i];
mincougradetext = "course1";
}
if (course1[i] > maxcougrade) {
maxcougrade = course1[i];
maxcougradetext = "course1";
}
if (course1[i] < minstugrade) {
minstugrade = course1[i];
minstugradetext = "student" + [i];
}
if (course1[i] > maxstugrade) {
maxstugrade = course1[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course2.length; i++) {
if (course2[i] < mincougrade) {
mincougrade = course2[i];
mincougradetext = "course2";
}
if (course2[i] > maxcougrade) {
maxcougrade = course2[i];
maxcougradetext = "course2";
}
if (course2[i] < minstugrade) {
minstugrade = course2[i];
minstugradetext = "student" + [i];
}
if (course2[i] > maxstugrade) {
maxstugrade = course2[i];
maxstugradetext = "student" + [i];
}
}
//calculate course average
for (i = 0; i < course0.length; i++) {
couavg += course0[i];
}
couavg = couavg / course0.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course0";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course0";
}
couavg = 0;
for (i = 0; i < course1.length; i++) {
couavg += course1[i];
}
couavg = couavg / course1.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course1";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course1";
}
couavg = 0;
for (i = 0; i < course2.length; i++) {
couavg += course2[i];
}
couavg = couavg / course2.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course2";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course2";
}
//calculate student average
for (i = 0; i < course0.length; i++) {
stuavgarr[i] += course0[i];
stuavgarr[i] += course1[i];
stuavgarr[i] += course2[i];
}
for (i=0; i < stuavgarr.length; i++) {
stuavgarr[i] = stuavgarr[i] / course0.length;
if (stuavgarr[i] < minstuavg) {
minstuavg = stuavgarr[i];
minstuavgtext = "student" + [i];
}
if (stuavgarr[i] > maxstuavg) {
maxstuavg = stuavgarr[i];
maxstuavgtext = "student" + [i];
}
}
document.getElementById("studmaxgrade").innerHTML = "Student that achieved the max grade is " + maxstugradetext
document.getElementById("studmingrade").innerHTML = "Student that achieved the min grade is " + minstugradetext
document.getElementById("studmaxavg").innerHTML = "Student that achieved the max average is " + maxstuavgtext
document.getElementById("studminavg").innerHTML = "Student that achieved the min average is " + minstuavgtext
document.getElementById("courmaxgrade").innerHTML = "The course in which the max grade is scored is " + maxcougradetext
document.getElementById("courmingrade").innerHTML = "The course in which the min grade is scored is " + mincougradetext
document.getElementById("courmaxavg").innerHTML = "The course in which the max average grade is scored is " + maxcouavgtext
document.getElementById("courminavg").innerHTML = "The course in which the min average grade is scored is " + mincouavgtext
}
</script>
The value of an input is a string, thus a + b will be interpreted as appending one string to another.
If you make sure the first parameter (a in this case) is an integer a + b will result in the two being mathematically adding the two
console.log( '0' + 1 + 2 + 3 + 4 ); //* outputs 01234
console.log( parseInt( 0 ) + 1 + 2 + 3 + 4 ); //* outputs 10
JSFiddle
Ok for a start you seem very confused about
document.getElementById
This does not address a javascript variable at all......
This literally "gets the document element by its id".
Here is an example of how to use it...
<html>
<img id='my_new_selfie' src='me.jpg'>
....
....
<script>
alert (document.getElementById('my_new_selfie').src)
</script>
This would simply pop up an alert with the text that describes the src of the
document object who's id is 'my_new_selfie'
that is....
[me.txt]
The reason that document.getElementById was introduced to javascript was to save developers learning the DOM (document object model) in order to access objects.
It allows you to simply give you object an id and change things about it using the id
In the above example I could use a script or button to change the image source
an example of this might be using the onclick event of another object on the page like a button...
onclick='document.getElementById('my_new_selfie').src='new_pic_of_me.JPG'
It is not used to identify variables in a javascript

How to count the number of section tags in an article tag?

I have been trying to write code that would use an embedded for loop to calculate the number of sections inside of each article (there is more than one so I can't use getID) in a document. When the button is clicked the code works but the numbers it calculates are completely off which means something isn't counting correctly. Here is my function:
<script>
function Calculations() {
var a = document.getElementsByTagName("article");
var s = 0;
var z = 0;
var x;
for (x = 0; x < a.length; x++) {
var cn = a[x].childNodes;
z++
for (i = 0; i < cn.length; i++) {
if (cn[i].nodeType == 1) {
if (cn[i].tagName == "P"); {
s++;
}
}
}
alert("Article " + z + " has " + s + " section.")
s = 0
}
alert("There are " + a.length + " total articles.")
}
</script>
Thank you so much for your help!

Javascript falling letters: Every other letter different direction

I'm having a hard time finding a way to insert falling letters into my code. My task is to have a text string and have all the even-placed letters fall from the top and the odd-placed letters fly from the bottom and come together to form the string in the center.
So for instance, I have: <span class="uName">John Doe</span>
I would like the letters: O, N, D, E to fall from the top.
Likewise: J H _ O to fly up from the bottom. (keeping their respective horizontal positions).
Here's what I have so far, however I'm fairly inexperienced with JavaScript/JQuery and I can't get it to run.
vertical = new Array(80);
var textPos = 0;
for(var i = 0; i < 80; ++i) {
vertical[i] = textPos;
textPos += 5;
}
function poz(){
document.getElementsByClassName("tops").style.top = '0px';
document.getElementsByClassName("bottoms").style.bottom = '0px';
animate();
}
function animate(){
for(var j = 0; j < 80; ++j) {
document.getElementsByClassName("tops").style.top = vertical[j] + "px";
document.getElementsByClassName("bottoms").style.bottom = vertical[j] + "px";
}
}
$('.uName').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="tops">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="bottoms">' + letters[i] + '</span>');
}
}
poz();
});
Thanks so much in advanced!
P.S. If this task can be achieved with just CSS3, I would much prefer that option but I'm not sure if it's possible.
//css
.bottoms{
margin-top:200px!important;
}
//Script
vertical = new Array(80);
var textPos = 0;
for(var i = 0; i < 80; ++i) {
vertical[i] = textPos;
textPos += 5;
}
function poz(){
// $(".tops").css('top','0px');
// $(".bottoms").css('bottom','0px');
//document.getElementsByClasjqsName("bottoms").style.bottom = '0px';
animate();
}
function animate(){
for(var j = 0; j < 80; ++j) {
//alert(vertical[j]);
//$(".tops").css('top',vertical[j]+'px');
//$(".bottoms").css('bottom',vertical[j]+'0');
if(vertical[j]<101){
$(".tops").animate({top:vertical[j]+'px'},500);
$(".bottoms").animate({bottom:vertical[j]+'px'},500);
$(".tops").css('position','relative');
$(".bottoms").css('position','relative');
$(".tops").css('float','left');
$(".bottoms").css('float','left');
}
// document.getElementsByClassName("tops").style.top = vertical[j] + "px";
// document.getElementsByClassName("bottoms").style.bottom = vertical[j] + "px";
}
}
$('.uName').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="tops">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="bottoms">' + letters[i] + '</span>');
}
}
poz();
});
//NEW Fiddle link http://jsfiddle.net/PP44C/7/
Now everything is fine as you want . check it

Generating Radio Button Result Depending On TextArea Value

A few days ago I did not manage to generate a result from my radio button, I managed to solve that problem now. My other problem is how do I generate ONLY few set of the radio button depending on TextArea value changes;
For Example in this code
<script language="javascript" type="text/javascript">
function generatetest() {
codeOne = document.docContainer.text1.value;
codeTwo = document.docContainer.number2.value;
function firstType(){
var codeFour = 0;
for( i = 0; i < document.docContainer.radio4.length; i++ )
{
if( document.docContainer.radio4[i].checked == true )
codeFour = document.docContainer.radio4[i].value;
}
var codeTen = 0;
for( i = 0; i < document.docContainer.radio10.length; i++ )
{
if( document.docContainer.radio10[i].checked == true )
codeTen = document.docContainer.radio10[i].value;
}
document.docContainer.textarea12.value = codeOne + codeTwo + codeFour + codeTen;
}
function secondType(){
var codeSix = 0;
for( i = 0; i < document.docContainer.radio6.length; i++ )
{
if( document.docContainer.radio6[i].checked == true )
codeFour = document.docContainer.radio6[i].value;
}
var codeEleven = 0;
for( i = 0; i < document.docContainer.radio11.length; i++ )
{
if( document.docContainer.radio11[i].checked == true )
codeTen = document.docContainer.radio11[i].value;
}
document.docContainer.textarea12.value = codeOne + codeTwo + codeSix + codeEleven
}
if (document.docContainer.number2.value="1")
{
firstType();
}
else if (document.docContainer.number2.value="2")
{
secondType();
}
}
</script>
The code is working, problem is, even though I insert the value on textarea "number2" as "2", the code still generate firstType() result
Am Im using wrong if-statement or what and how do I go around about this?
Your code could be more fun to read, but Putting quotes around your numbers is causing javascript to treat them like text. Is this what you want to be doing?

Categories