Vito
Vito

Reputation: 728

Fraction number in Javascript

I'm working on a JavaScript project in which I need to display an array of numbers. This numbers can be integers or fractions. I need to display the fraction in the classic way, I mean, the top number, below a line and below the other number, as shown in this example:

http://jsfiddle.net/xW7d8/

The thing is that the array that I was talking about is the one that contains the numbers, and using Jquery I change the text of a div so I display the numbers, just like this:

97,30,58,53,42,60,77,11

69/90,10/32,74/74,9/54,69/2,17/86,62/72,55/85

First thing that I do is to fill the array, save the numbers to a string, and then, change the text of the div. Below is what I do in code:

var array = fillArray();//this fill an array of numbers, integers or fractions
var stringArray;//will contains the numbers of the array
for(var i=0;i<array.length;i++)
{
  stringArray+= array[i];
}
$("#num1").text(stringArray);

In this way, I cannot put a div ID to each number, if I try to do this its not interpreted as HTML, what I take is the text of the HTML tag itself, for example, for the number 1/2 if I try to do:

<span class="fraction">1/2</span>

I literally get the span class, it is not read as HTML code.

I tried also to generate the format for the fraction in the JavaScript code itself doing this:

var number = x + "\n" + "-" + "\n" + y;

This do not work, it don't recognize the "\n", neither "\r", etc (if I try with < br/ > is written literally)

Is there some way to get the fraction numbers the way I want? Probably I will need to generate the number in this format in the JavaScript itself without the help of the HTML tags.

Upvotes: 3

Views: 1642

Answers (2)

Lee Meador
Lee Meador

Reputation: 12985

Try this with the string containing the tags. It should begin with a tag, though:

$("#num1").html(stringArray);

But since your fiddle rewrites the div with the fraction class you probably just want to generate the whole html of the fractions yourself. <span class="top">1</span><span class="bottom">2</span> instead of doing the <span class='fraction'>1/2</span> and then running the code to convert.

Upvotes: 3

Lochemage
Lochemage

Reputation: 3974

Sounds to me like you want to use JQuery's html() function instead of text()

$("#num1").html(stringArray);

Does this help?

Upvotes: 1

Related Questions