MarkoD
MarkoD

Reputation: 43

javascript for loop & function

I'm trying to create a page with a button that calls a function when clicked to use a for loop. Needs to loop through the code 5 times and return a page that looks like:

$
$$
$$$
$$
$

I'm struggling to get my head around it, very few examples out there that don't just focus on integers. Her's where I'm at...

<html>
<head>
  <button onclick="myFunction()">Click This Button</button>


</head>

<body>
  <p id="dollar"></p>

  <script type = "javascript/text">
    function myFunction() {
    var a;
    if(a===0) || (a===4) {
        document.write("$" + <br />);
    }
    if(a===1) || (a===3) {
        document.write("$$" + <br />);
    }   
    if (a===3) {
        document.write ("$$$" + <br />);
    }
    for (a = 0; a < 5; a++){

    }

    document.getElementById("dollar").innerHTML = text;

    }

  </script>


</body>
</html>

Upvotes: 0

Views: 126

Answers (6)

ankhzet
ankhzet

Reputation: 2570

As example, use array of values:

var patterns = ['$', '$$', '$$$', '$$', '$'];
function myFunction() {
    var text = '';
    for (var i = 0; i < patterns.length; i++)
      text+= patterns[i] + '<br />';

    document.getElementById("dollar").innerHTML = text;
}

Note: the same result can be achieved by getting rid of loop:

var patterns = ['$', '$$', '$$$', '$$', '$'];
function myFunction() {
    document.getElementById("dollar").innerHTML = patterns.join('<br />') + '<br />';
}

Note: just playing...

var waiter = function (selector, framerate, patterns) {
  var element = document.querySelectorAll(selector)[0];
  
  element.style.css = "display: none";
  
  var timer, frame;
  
  return {
    tick: function () {
        element.innerHTML = '[' + patterns[frame].replace(/\s/g, '&nbsp;') + ']';
        frame = ++frame % patterns.length;
    },

    show: function () {
      frame = 0;
      if (timer)
        window.clearInterval(timer);
      
      timer = window.setInterval(function () {
        this.tick();
      }.bind(this), framerate);
      
      element.style.css = "display: block";
    },
  }
};

waiter('#waiter', 50, [
    '> -------',
    '>> ------',
    ' >> -----',
    '- >> ----',
    '-- >> ---',
    '--- >> --',
    '---- >> -',
    '----- >> ',
    '------ >>',
    '------- >',
    '------- <',
    '------ <<',
    '----- << ',
    '---- << -',
    '--- << --',
    '-- << ---',
    '- << ----',
    ' << -----',
    '<< ------',
    '< -------',
  ]).show();

waiter('#waiter2', 50, [
    '> -------',
    '>> ------',
    ' >> -----',
    '- >> ----',
    '-# >> ---',
    '-#- >> --',
    '-#-# >> -',
    '-#-#- >> ',
    '-#-#-# >>',
    '-#-#-#- >',
    '-#-#-#- <',
    '-#-#-# <<',
    '-#-#- << ',
    '-#-# << -',
    '-#- << #-',
    '-# << -#-',
    '- << #-#-',
    ' << -#-#-',
    '<< #-#-#-',
    '< -#-#-#-',
    '> -#-#-#-',
    '>> #-#-#-',
    ' >> -#-#-',
    '- >> #-#-',
    '-- >> -#-',
    '--- >> #-',
    '---- >> -',
    '----- >> ',
    '------ >>',
    '------- >',
    '------- <',
    '------ <<',
    '----- << ',
    '---- << -',
    '--- << --',
    '-- << ---',
    '- << ----',
    ' << -----',
    '<< ------',
    '< -------',
  ]).show();

waiter('#waiter3', 100, [
    '>        ',
    '>>       ',
    ' >>      ',
    '- >>     ',
    '-- >>    ',
    '--- >>   ',
    '---- >>  ',
    '----- >> ',
    '------ >>',
    '------- >',
    '-------- ',
    '---------',
    '<--------',
    ' <-------',
    '( =------',
    ' ( =-----',
    '  ( <----',
    '   ( <---',
    '    ( =--',
    '     ( =-',
    '      ( <',
    '       ( ',
    '        (',
    '         ',
  ]).show();
  
if (!String.prototype.x) {
  String.prototype.x = function (times) {
    return Array(times + 1).join(this);
  }
}
  
  
var blink =
    '  -___-  |'.x(4) +
    '  -___o  |' +
    '  -___O  |'.x(4) +
    '  -___o  |' +
    '  -___-  |' +
    '  o___o\' |' +
   ('  O___O" |'.x(2) +
    '  -___-" |').x(2) +
    '  O___O" |'.x(10) +
    '  -___-" |' +
    '  O___O  |'.x(10) +
    '  o___o  |'.x(10) +
    '  -___-  |'.x(10) +
    '  -___o  |'.x(16) +
    '  -___-  |'.x(10);

waiter('#waiter4', 100, blink.replace(/^\||\|$/, '').split('|')).show();
.waiter {
  font-family: Consolas, Courier;  
}
<div class="waiter" id="waiter"></div>
<div class="waiter" id="waiter2"></div>
<div class="waiter" id="waiter3"></div>
<div class="waiter" id="waiter4"></div>

Upvotes: 2

Mohammad Javad
Mohammad Javad

Reputation: 584

use this code for any number 5 or 7 or 9 or....

  function myFunction(cnt) {
    var text = '';
    for (var i = 0; i < cnt; i++){
        if(i<(cnt/2)){
            for (var j = 0;  j< (i+1); j++){
                text+= "$";
            }
            text+= '<br />';
        }
        else{
            for (var j = 0;  j< (cnt-i); j++){
                text+= "$";
            }
            text+= '<br />';
        }
    }
    document.getElementById("dollar").innerHTML = text;
}

for example:

    myFunction(11);

result :

$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$
$$$$
$$$
$$
$

Example

    function callmyFunction(){
        var tmp=document.getElementById("countDollar").value;
        myFunction(+tmp);
    }
    function myFunction(cnt) {
        var text = '';
        for (var i = 0; i < cnt; i++){
            if(i<(cnt/2)){
                for (var j = 0;  j< (i+1); j++){
                    text+= "$";
                }
                text+= '<br />';
            }
            else{
                for (var j = 0;  j< (cnt-i); j++){
                    text+= "$";
                }
                text+= '<br />';
            }
        }
        document.getElementById("dollar").innerHTML = text;
    }
<input id="countDollar" value="15" />
<button onclick="callmyFunction()" >Click me!</button>

<div id='dollar'>

Upvotes: 2

Hasan Tareque
Hasan Tareque

Reputation: 1741

This code is work the way you wanted to acheive it. However, its not recommended. Your html code wasn't correct as you put the button on head and your javascript condition wasn't correct as you put the (). hope this helps ...

<head>
    <script>
        function myFunction() {

        var a;
        for(a=0; a<5; a++){

        if(a===0 || a===4) {
        document.write("$<br/>");
        }
        if(a===1 || a===3) {
        document.write("$$<br>");
        }   
        if (a===2) {
        document.write ("$$$<br/>");
        }
        }
        }
    </script>
</head>

<body>
    <button type="button" onclick="myFunction()">Click This Button</button>

</body>

Upvotes: 1

Mitch
Mitch

Reputation: 321

This is a fixed version using the solution you've gone for above. However, ankhzet's answer is a cleaner approach all round.

<html>
<head>
  <!-- script in head -->
  <script type = "javascript/text">
    function myFunction() {
      var a;
      var text = "";

      for ( a = 0; a < 5; a++ ){
        // if statements within the loop
        if( a === 0 || a === 4 ) { // All conditionals must be within one set of parenthesis. You can have others within, but all must be contained in one.
          text += "$<br />";
        }
        if( a === 1 || a === 3 ) {
          text += "$$<br />";
        }   
        if ( a === 2 ) {
          text += "$$$<br />";
        }
      }
      document.getElementById( "dollar" ).innerHTML = text;
    }
  </script>
</head>
<body>
  <!-- button in body -->
  <button onclick="myFunction()">Click This Button</button>
  <p id="dollar"></p>
</body>
</html>

Upvotes: 1

durbnpoisn
durbnpoisn

Reputation: 4659

Your actionable stuff is outside your loop.

    function thisThing(){
        var finalIs =""
        for (a = 0; a < 5; a++){    
            if((a==0) || (a==4)) {
              finalIs += "$<br />";
           }
          if (a==3) {
                finalIs += "$$$<br />";
            }
          if((a==1) || (a==3)) {
                finalIs += "$$<br />";
            }   


        }
document.getElementById("dollar").innerHTML = finalIs;
        }

Also, you do not need to declare "a" since you are declaring it when you start your loop. Also, your document write statements were incorrect. You were setting them up as if <br /> were a variable. Which it is not. It's just the rest of the string.

EDIT: this final version works perfect. All errors fixed. You can see the differences for yourself.

Upvotes: 2

j08691
j08691

Reputation: 207861

Here's a simple way using a single loop, a temp variable, and an array:

 function myFunction() {
   for (var a = 1; a <= 5; a++) {
     x = a;
     if (x > 3) x = 6 - a;
     document.getElementById("dollar").innerHTML += Array(x + 1).join("$") + '<br />';
   }
 }
<button onclick="myFunction()">Click This Button</button>
<p id="dollar"></p>

Upvotes: 1

Related Questions