I want to use a for loop to display
*
**
***
in javasript does anybody know how?

Try this demo:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
<title>JavaScript DEMO ( For loop with icremented characters )</title>
<script type="text/javascript">
<!-- 
var show, ar, x, num = 1;

function display() {
ar = "***********";
for ( x = (( ar.length ) - 1 ); x != 0; x-- ) {
show = ( document.getElementById ) ? document.getElementById("output") : document.all.output;
show.innerHTML += num + ". " + ( ar.substr( x, ar.length )) + "<br>"; // Incremented characters and numbers;
  num++; } 
}

if (window.addEventListener)
window.addEventListener('load',display,false);
else if (window.attachEvent)
window.attachEvent('onload',display);
else
window.onload = display;
// -->
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

JUST WRITE THE BLOW SCRIPT UNDER HEAD TAG:

<script type="text/javascript">
    for(var i=1;i<=10;i++)
    {
    var str='';
    for(var j=0;j<i;j++)
     str=str + '*';
     document.writeln(str+'<br/>');
     str='';
    }
    </script>

JUST CHANGE THE RED COLOR NUMBER TO VARRY THE LINE NUMBER.

The function showStars() below uses DOM methods to build and insert lines of asterisks and will allow you to specify:

  • the id of the containing div in which you want your asterisks to appear (first paramerter).
  • the maximum number of asterisks (second parameter).
  • their appearance (CSS class .mystars).
<html>
<head>
.......
<style type="text/css">
#stars p { margin:0; font-family:verdana,arial,helvetica; color:darkorange; font-size:20pt; letter-spacing:0.5em; line-height:1.0em; }
</style>
<script type="text/javascript">
function showStars(containerID, maxStars){
  var starArray = [];
  for(var i=0; i<maxStars; i++){
    starArray.push('*');
    var p = document.createElement('p');
    p.appendChild(document.createTextNode(starArray.join('')));
    document.getElementById(containerID).appendChild(p);
  }
}
onload = function(){
  showStars("stars", 10);
}
</script>
.......
</head>
<body>
.......
<div id="stars"></div>
.......
</body>
</html>

You could reduce the whole thing down to a simple writeln() approach but it's not as elegant, and has no scope for multiple usage on page.

No need to bother with addEventListener or attachEvent as onload is understood by all major browsers (Doug Crockford says so).

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.