Tuesday, 19 March 2013

Add Line Number to Text Using Javascript


Add Line Number to Text Using Javascript


You can add Line Numbers to a text inside a Multiline Textbox/TextArea using the following Javascript:



<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Add Line Number Using Javascript</title>
    
    <script language="JavaScript" type="text/javascript">
        <!--
        function main()
        {
            var test_string = new Array();
            test_string = document.forms[0].inputString.value.split( '\n' );
            var result = "";

   for( var ix = 0; ix < test_string.length; ix++ )
   {
    result += fixNumber( ix, test_string.length ) + test_string[ ix ];
    if( ix != test_string.length - 1)
    {
     result += "\n";
    }
   }
            document.forms[0].output.value = result;
        }

  function fixNumber( ix, total )
  {
   var temp = total.toString();
   var width = temp.length;
   var outputNum = ( ix + 1 ).toString();

   while( outputNum.length < width )
   {
    outputNum = " " + outputNum;
   }

   return outputNum + ": ";
  }
        //-->
</script>
    
</head>
<body>
<h1>Insert Line Numbers</h1>
<form action="javascript:main();">
<textarea cols="100" rows="12" name="inputString">
Lorem
ipsum
dolor
sit
amet,
consetetur
sadipscing
elitr,
sed
diam
nonumy
eirmod</textarea>
<br>
<textarea cols="100" rows="12" name="output"></textarea>
<br>
<input type="Submit"></form>
</body>
</html>






No comments:

Post a comment

Thank You for Your Comments. We will get back to you soon.

back to top