Internet JavaScript string in HTML

asbjos

tuanibrO
Addon Developer
Joined
Jun 22, 2011
Messages
696
Reaction score
259
Points
78
Location
This place called "home".
Hello, there!

I am making a vector cross product calculator. I do it with JavaScript and show it in HTML.

I have made the converter work, but when I want my small program show me the result using document.write(), it deletes the previous page while pasting the result. How do I get JavaScript paste in a line without deleting the whole page?

I know that I could use alert(), but it didn't look so nice.

Remember that I am an absolute beginner, so no advanced commands, please.

Here is the calculator.

My script:
HTML:
<!DOCTYPE hmtl>

<html>

<head>
	<title>Cross product.</title>
</head>

<body style="background-color:#E4E4E4; font-family:Calibri; color:#271828">

<h1>Cross product!</h1>

<!-- Some Norwegian text without importance -->
<p>
Hei! Dette er en vektorkryssproduktkalkulator. Akkurat som navnet antyder krysser den vektorer for å finne vektorkryssproduktet. Prøv det ut!
</p>

<script>
function cross()
{
// Type vector nr.1
var x1 = prompt("Type x-value for vector nr.1.");
var y1 = prompt("Type y-value for vector nr.1.");
var z1 = prompt("Type z-value for vector nr.1.");
document.writeln("Vector nr. 1 is [" + x1 + ", " + y1 + ", " + z1 + "]. ");

// Type vector nr.2
var x2 = prompt("Type x-value for vector nr.2.")
var y2 = prompt("Type y-value for vector nr.2.")
var z2 = prompt("Type z-value for vector nr.2.")
document.writeln(""Vector nr. 2 is [" + x2 + ", " + y2 + ", " + z2 + "]. ");

// Crossing two and two values
var crossx1 = y1 * z2
var crossx2 = z1 * y2

var crossy1 = z1 * x2
var crossy2 = x1 * z2

var crossz1 = x1 * y2
var crossz2 = y1 * x2

// Subtract and find x, y and z.
var x = crossx1 - crossx2

var y = crossy1 - crossy2

var z = crossz1 - crossz2

// The resulting cross product.
var vector = "[" + x + ", " + y + ", " + z + "]"

// Print the result
document.writeln("Your vector cross product became " + vector + ".");
}
</script>


<p> </p>

<button type="button" onclick="cross();">Calculate!</button>

<p> </p>

<!-- Refresh button for when it wasn't a function, but ran at page opening, so not necessary now -->

<button type="button" onclick="history.go(0)">New cross product. Will remove previous calculations!</button>

</body>

</html>

Thank you for your time.
 

orb

New member
News Reporter
Joined
Oct 30, 2009
Messages
14,020
Reaction score
4
Points
0
You can for example use DHTML to change some element on the page (for example with innerHTML property of the element), or use read-only input form element and set its value. There are also other ways (all use DOM).


Not a complete example using input element, but you should know which part to put where:
Code:
Vector 1:<input id="vector1" type="text" readonly="readonly" /><br />
Vector 2:<input id="vector2" type="text" readonly="readonly" /><br />
Cross product:<input id="crosspr" type="text" readonly="readonly" />

{...}

var element;
element = document.getElementById ('vector1');
element.value = '[' + x1 + ', ' + y1 + ', ' + z1 + ']';

{...}

element = document.getElementById ('vector2');
element.value = '[' + x2 + ', ' + y2 + ', ' + z2 + ']';

{...}

element = document.getElementById ('crosspr');
element.value = '[' + x + ', ' + y + ', ' + z + ']';

And an example using innerHTML:
Code:
Vector 1: <span id="vector1">Empty</span><br />
Vector 2: <span id="vector2">Empty</span><br />
Cross product: <span id="crosspr">None</span>

{...}

var element;
element = document.getElementById ('vector1');
element.innerHTML = '[' + x1 + ', ' + y1 + ', ' + z1 + ']';

{...}

element = document.getElementById ('vector2');
element.innerHTML = '[' + x2 + ', ' + y2 + ', ' + z2 + ']';

{...}

element = document.getElementById ('crosspr');
element.innerHTML = '[' + x + ', ' + y + ', ' + z + ']';
 

kuddel

Donator
Donator
Joined
Apr 1, 2008
Messages
2,064
Reaction score
508
Points
113
Hi asbjos,

how about accessing the DOM instead of using alert/prompt?

I've took the liberty to write your calculus code in three different ways:
1. as you did it
2. with JavaScript Maps (or Objects as they are also called) wich have indices 'x', 'y' and 'z'
3. with Arrays wich have (numeric) indices 0, 1, and 2.

HTML:
<!DOCTYPE hmtl>
<html>
<head>
    <title>Cross product.</title>
  <script>
    // VERY simple write to DIV function (works in most browsers!)
    function writeToResultArea (txt)
    {
      var element = document.getElementById("result_area");
      element.innerHTML = txt;
    }

    function cross()
    {
      // Type vector nr.1
      var x1 = parseFloat( document.getElementById('a_x').value );
      var y1 = parseFloat( document.getElementById('a_y').value );
      var z1 = parseFloat( document.getElementById('a_z').value );

      // Type vector nr.2
      var x2 = parseFloat( document.getElementById('b_x').value );
      var y2 = parseFloat( document.getElementById('b_y').value );
      var z2 = parseFloat( document.getElementById('b_z').value );

      // Crossing two and two values
      var crossx1 = y1 * z2
      var crossx2 = z1 * y2

      var crossy1 = z1 * x2
      var crossy2 = x1 * z2

      var crossz1 = x1 * y2
      var crossz2 = y1 * x2

      // Subtract and find x, y and z.
      var x = crossx1 - crossx2

      var y = crossy1 - crossy2

      var z = crossz1 - crossz2

      // The resulting cross product.
      var vector = "[" + x + ", " + y + ", " + z + "]"
      // Easier:
      // var vector = [ x, y, z ].join();

      // Print the result
      writeToResultArea("Your vector cross product became " + vector + ".");
    }

    function crossArray ()
    {
      var a = [
        parseFloat( document.getElementById('a_x').value ),
        parseFloat( document.getElementById('a_y').value ),
        parseFloat( document.getElementById('a_z').value )
      ];
      var b = [
        parseFloat( document.getElementById('b_x').value ),
        parseFloat( document.getElementById('b_y').value ),
        parseFloat( document.getElementById('b_z').value )
      ];

      var cross = [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0]
      ];
      writeToResultArea( JSON.stringify(cross) );
    }

    function crossMap ()
    {
      var a = {
        x : parseFloat( document.getElementById('a_x').value ),
        y : parseFloat( document.getElementById('a_y').value ),
        z : parseFloat( document.getElementById('a_z').value )
      };
      var b = {
        x : parseFloat( document.getElementById('b_x').value ),
        y : parseFloat( document.getElementById('b_y').value ),
        z : parseFloat( document.getElementById('b_z').value )
      };

      var cross = {
        x : a.y * b.z - a.z * b.y,
        y : a.z * b.x - a.x * b.z,
        z : a.x * b.y - a.y * b.x
      };

      writeToResultArea( JSON.stringify(cross) );
    }
  </script>
</head>
<body style="background-color:#E4E4E4; font-family:Calibri; color:#271828">

  <h1>Cross product!</h1>

  <!-- Some Norwegian text without importance -->
  <p>
  Hei! Dette er en vektorkryssproduktkalkulator. Akkurat som navnet antyder krysser den vektorer for å finne vektorkryssproduktet. Prøv det ut!
  </p>

  <p> </p>

  <!-- Refresh button for when it wasn't a function, but ran at page opening, so not necessary now -->

  <button type="button" onclick="history.go(0)">New cross product. Will remove previous calculations!</button>

  <p> </p>

  <p>
    Vector A:<br/>
    X:<input id="a_x" value="0"/>
    Y:<input id="a_y" value="0"/>
    Z:<input id="a_z" value="0"/>
  </p>
  <p>
    Vector B:<br/>
    X:<input id="b_x" value="0"/>
    Y:<input id="b_y" value="0"/>
    Z:<input id="b_z" value="0"/>
  </p>

  <button type="button" onclick="cross();">Calculate!</button>
  <button type="button" onclick="javascript:crossMap();">Calculate (w/ Maps)!</button>
  <button type="button" onclick="javascript:crossArray();">Calculate (w/ Array)!</button>

  <div id="result_area"></div>

</body>

</html>

For your question the function "writeToResultArea" does write to the DIV-Element called "result_area" (wich is the 'id' of the DIV element)
You could also have accessed it with the following combination:
HTML:
<div name="some_name"></div>
document.getElementByName('some_name')

/Kuddel

---------- Post added at 18:25 ---------- Previous post was at 18:10 ----------

By the way: here's another one with a 'clear Inputs' Button / function:

...I've used JSON.stringify(...) to easily output the results, but you could also put the individual components of the cross-product to individual
fields in the output. Just add some result fields (e.g. readOnly input elements), give them (unique) IDs and use the document.getElementById(...) function to access them from your JavaScript!

HTML:
<!DOCTYPE hmtl>
<html>
<head>
    <title>Cross product.</title>
  <script>
    // VERY simple write to DIV function (works in most browsers!)
    function writeToResultArea (txt)
    {
      var element = document.getElementById("result_area");
      element.innerHTML = txt;
    }

    function clearInputs ()
    {
      var ids = ['a_x','a_y','a_z',
                 'b_x','b_y','b_z'
                ];
      ids.forEach(function (id) {
        document.getElementById(id).value = 0;
      });
    }

    function cross()
    {
      // Type vector nr.1
      var x1 = parseFloat( document.getElementById('a_x').value );
      var y1 = parseFloat( document.getElementById('a_y').value );
      var z1 = parseFloat( document.getElementById('a_z').value );

      // Type vector nr.2
      var x2 = parseFloat( document.getElementById('b_x').value );
      var y2 = parseFloat( document.getElementById('b_y').value );
      var z2 = parseFloat( document.getElementById('b_z').value );

      // Crossing two and two values
      var crossx1 = y1 * z2
      var crossx2 = z1 * y2

      var crossy1 = z1 * x2
      var crossy2 = x1 * z2

      var crossz1 = x1 * y2
      var crossz2 = y1 * x2

      // Subtract and find x, y and z.
      var x = crossx1 - crossx2

      var y = crossy1 - crossy2

      var z = crossz1 - crossz2

      // The resulting cross product.
      var vector = "[" + x + ", " + y + ", " + z + "]"
      // Easier:
      // var vector = [ x, y, z ].join();

      // Print the result
      writeToResultArea("Your vector cross product became " + vector + ".");
    }

    function crossArray ()
    {
      var a = [
        parseFloat( document.getElementById('a_x').value ),
        parseFloat( document.getElementById('a_y').value ),
        parseFloat( document.getElementById('a_z').value )
      ];
      var b = [
        parseFloat( document.getElementById('b_x').value ),
        parseFloat( document.getElementById('b_y').value ),
        parseFloat( document.getElementById('b_z').value )
      ];

      var cross = [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0]
      ];
      writeToResultArea( JSON.stringify(cross) );
    }

    function crossMap ()
    {
      var a = {
        x : parseFloat( document.getElementById('a_x').value ),
        y : parseFloat( document.getElementById('a_y').value ),
        z : parseFloat( document.getElementById('a_z').value )
      };
      var b = {
        x : parseFloat( document.getElementById('b_x').value ),
        y : parseFloat( document.getElementById('b_y').value ),
        z : parseFloat( document.getElementById('b_z').value )
      };

      var cross = {
        x : a.y * b.z - a.z * b.y,
        y : a.z * b.x - a.x * b.z,
        z : a.x * b.y - a.y * b.x
      };

      writeToResultArea( JSON.stringify(cross) );
    }
  </script>
</head>
<body style="background-color:#E4E4E4; font-family:Calibri; color:#271828">

  <h1>Cross product!</h1>

  <!-- Some Norwegian text without importance -->
  <p>
  Hei! Dette er en vektorkryssproduktkalkulator. Akkurat som navnet antyder krysser den vektorer for å finne vektorkryssproduktet. Prøv det ut!
  </p>

  <p> </p>

  <button type="button" onclick="javascript:clearInputs();">Clear Inputs</button>

  <p> </p>

  <p>
    Vector A:<br/>
    X:<input id="a_x" value="0"/>
    Y:<input id="a_y" value="0"/>
    Z:<input id="a_z" value="0"/>
  </p>
  <p>
    Vector B:<br/>
    X:<input id="b_x" value="0"/>
    Y:<input id="b_y" value="0"/>
    Z:<input id="b_z" value="0"/>
  </p>

  <button type="button" onclick="cross();">Calculate!</button>
  <button type="button" onclick="javascript:crossMap();">Calculate (w/ Maps)!</button>
  <button type="button" onclick="javascript:crossArray();">Calculate (w/ Array)!</button>

  <div id="result_area"></div>

</body>

</html>
 
Last edited:
Top