SyntaxError: invalid flag after regular expression and white screen - javascript

I can't figure out why my page will not work. It just gives me a white screen when I try to load it. Is there a code I am missing? I don't know if my spaces matter either. Here is my code:
<!DOCTYPE html>
<html>
<head><body>
<title>Initializing an Array</title>
<style type="text/css">
table {width:10em}
th {text-align:left}
</style>
<script language="JavaScript">
<!--
{//create (declare) two new arrays
var n1=new Array(5); //allocate five-element Array
var n2=new Array (); //allocate empty Array
//assign values to each element of Array n1
for ( var i = 0; i <n1.length; ++i )
n1[ i ] = i;
//create and initialize five elements in Array n2
for ( i=0; i <5; ++i )
n2[ i ] = i;
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
//output the heading followed by a two-column table
//containing subscripts and elements of "theArray"
function outputArray (heading,theArray)}
{
document.writeln("<h2>"+heading+"</h2>");
document.writeln("table border=\"1\"");
document.writeln("<thead><th>Subscripts</th>"+"<th>Value</th></thead> <tbody>");
//output the subscript and value of each array element
for ( var i = 0; i <theArray.length; i++ )
document.writeln("<tr><td>+i+"</td><td>"+theArray[i]+"</td></tr>");
document.writeln("/tbody></table>");
} //end function outputArray
//-->
</script>
</head></body>
</html>
Please help! Thanks.

You have broken HTML and invalid Javascript.
<script language="JavaScript">
For your DOCTYPE of html, there is no need to specify any attributes to a <script> tag except src, and that is only needed if you are loading an external script file. And there is no attribute language. You likely meant type="text/javascript" but that is the default and therefore redundant.
<!--
You can't have HTML comments inside a <script> block. You are telling the browser that what is inside the <script> block is Javascript, then you putting invalid javascript. There will likely be errors displayed in the console.
Your example, tidied up, would look something like this:
<script>
// create (declare) two new arrays
var n1 = new Array(5); //allocate five-element Array
var n2 = new Array(); //allocate empty Array
// assign values to each element of Array n1
for (var i = 0; i < n1.length; ++i) {
n1[ i ] = i;
}
// create and initialize five elements in Array n2
for (i=0; i < 5; ++i) {
n2[ i ] = i;
}
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
// output the heading followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray (heading, theArray) {
var html = '<h2>' + heading + '</h2>';
html += '<table border="1">';
html += '<thead><th>Subscripts</th><th>Value</th></thead>';
html += '<tbody>';
// output the subscript and value of each array element
for (var i = 0; i < theArray.length; i++) {
html += '<tr><td>' + i + '</td><td>' + theArray[i] + '</td></tr>';
}
html += '</tbody></table>';
var div = document.createElement('div');
div.innerHTML = html;
document.body.appendChild(div);
}
</script>

You forgot quote " and on the next line < in </tbody> in last for loop.
document.writeln("<tr><td>"+i+"</td><td>"+theArray[i]+"</td></tr>");
^
document.writeln("</tbody></table>");
^

Of course nothing gets displayed, the base HTML layout is completely wrong.
You wrote :
<head>
<body>
(all the stuff)
</head>
</body>
It should be :
<head>
(scripts.....)
</head>
<body>
(HTML....)
</body>

Related

How can I print a new line in JS without using document.write?

I would like to print a new line in JS, but I can't figure out how to do it without document.write. I need to do it without this because I'm using buttons to call functions, and when I use doc.write, it erases the page and displays the results of the function on its own.
<h3>$$$$$</h3>
<span id = "$"></span>
<button onclick="prob2()">Submit</button>
<script type="text/javascript">
function prob2(){
n = parseInt(prompt("Enter number: "));
for(var i=0;i<n;i++){
for(var j=0;j<=i;j++){
document.getElementById("$").innerHTML = "$";
}
console.log("\n");
}
};
Rather than having console.log there, I want to print a line break on the screen so that my output looks like this:
$
$$
$$$
...
EDIT:
Based on Anurag's first suggestion, I built a string and used it with innerHTML to achieve my desired output.
function prob2(){
var str = "";
var num = parseInt(prompt("Enter number: "));
for(var i=0;i<num;i++){
for(var j=0;j<=i;j++){
str += "$";
}
str += "<br>";
}
document.getElementById("$").innerHTML = str;
};
His second suggestion that I accepted as the answer also works!
Here's one way to do it:
function generate() {
document.getElementById("$").innerHTML = ""
var n = parseInt(prompt("Enter number: ")), str = "", currStr = "";
for (var i = 0; i < n; i++) {
str = "", currStr = document.getElementById("$").innerHTML
for (var j = 0; j <= i; j++) {
str+= "$"
document.getElementById("$").innerHTML = currStr + str + "<br/>";
}
}
};
<h3>Incremental $</h3>
<span id="$"></span>
<button onclick="generate()">Generate</button>
I interpreted the question differently. I thought the purpose was to replace the use of the document.write() statement.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- For: https://stackoverflow.com/questions/62742502/how-can-i-print-a-new-line-in-js-without-using-document-write -->
<style>
p { background-color: lime; }
pre { border: 1px solid red;}
div { border: 3px dotted blue }
</style>
</head><body>
<script>
newLine = (tag,msg) => {
var elem = document.createElement(tag);
elem.appendChild(document.createTextNode(msg));
document.body.appendChild(elem);
// Note: .body. could be a different element or another parameter added to function
}
newLine('p','New line has been created.');
newLine('pre','And then another.');
newLine('div','And then one final new line to display.');
</script>
</body></html>
Remove the CSS styling as it was only added for emphasis.

How do I dynamically change a key in a for loop

I want to be able to change the key in a for loop, it's hard to explain what I need so I made a demo based on the https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for play ground.
I need to be able to swap the keys depending on logic because the array data keys will alter depending on the json feed therefore it won't be possible to hard code the keys.
Thanks in advance
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
var keyToChoose = "name"; /// or I could choose "colour"
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
You use it like this.
text += cars[i][keyToChoose] + "<br>";
now it depends on the value of the variable keyToChoose.
You can use a global variable to decide your key.
<script>
// 1 = name , 2 = colour
var currentKey = 1;
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
// the key is chosen based on the currentKey which can be made a global variable and changed dynamically.
var keyToChoose = currentKey === 1 ? "name" : "colour";
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>

Creating HTML list using loop in Javascript

I've got an array in Javascript that I want to print to screen which is: (my function for ro[j] is simplified in this example, but that doesn't matter)
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
$('.result2').html(ro[j]);
}
</script>
But this doesn't work as I think it keeps replacing the div with each loop rather than adding to the div. Is there a good way to implement this? I thought you could try something like this:
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
if(j==0){
$('.result2').html(ro[j]);
}else{
var res = $('.result2').val();
$('.result2').html(res + ro[j]);
}
}
</script>
but this doesn't work since you can't seem to call the result of the script midway through the script? Or I just made a mistake, I'm not sure. Any help would be great!
edit: forgot a semicolon
A list element (ul or ol) should be used for lists as it's more semantically correct:
<ul id="result2"></ul>
Using es6 syntax you can append elements to that list like this:
const ro = [...Array(49).keys()]; // Just setting up a sample array
for (r of ro) {
let li = document.createElement('li');
li.innerHTML = r;
document.getElementById('result2').appendChild(li);
}
This will place the numbers vertically in the screen.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result2"></div>
<script type='text/javascript'>
var ro = [];
for (var j = 0; j <= 49; j++) {
ro.push(j);
$('.result2').append(ro[j] + '<br />');
}
</script>
</body>
</html>

Javascript function to add to or splice array

I have two buttons, each button adds an array to the array orderArray. This works fine and the array is displayed as a html table. When the table is output a button is also created. This buttons purpose is to remove the array associated with it, and hence remove a line from the table.
This works fine, but after removing part of the array with .splice it is not possible to then add more to the array, it just throws "cannot read property length".
You can see in the console that the array is spliced and that the length value is correct but the error still persists. I am clearly not getting something here, as I thought that as the loop calls myArray.length it would get the right length every time.
Here is the js:
var orderArray = [];
var orderNumber = 0;
var theOrder = [];
var total = 0;
function orderUpdate(item,price){
theOrder = [item, price];
orderArray[orderNumber] = theOrder;
orderNumber++;
}
function makeTable(myArray) {
var result = "<table border=2 id=orderTable>";
console.log(myArray.length);
for(var i = 0; i < myArray.length; i++) {
result += "<tr id='row" + i + "'>";
for(var j = 0; j < myArray[i].length; j++){
result += "<td>" + myArray[i][j] + "</td>";
}
result += "<td><button onclick='removeLine(" + i + ")'>Remove</button></td></tr>";
}
result += "</table>";
console.log(myArray);
return result;
}
$( "#LongB" ).click(function() {
orderUpdate("Long Black", 2.50);
$("#ordered").html(makeTable(orderArray));
});
$( "#FlatW" ).click(function() {
orderUpdate("Flat White", 3.50);
$("#ordered").html(makeTable(orderArray));
});
function removeLine(arrayIndex){
orderArray.splice(arrayIndex, 1);
console.log(orderArray);
$("#ordered").html(makeTable(orderArray));
}
and the html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSPOS</title>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<button id="LongB">Long Black</button>
<button id="FlatW">Flat White</button>
<h3>Ordered:</h3>
<div id="ordered"></div>
<script src="js/stuff.js"></script>
</body>
</html>
and here it is as a fiddle.
This is because you are increasing the orderNumber when you add new item but when you remove the item you forgot to decrease the orderNumber so you got the error because index doesn't exists in array:-
function removeLine(arrayIndex){
orderArray.splice(arrayIndex, 1);
console.log(orderArray);
orderNumber--; //add this line
$("#ordered").html(makeTable(orderArray));
}
Demo
Try substituting orderArray.push(theOrder); for orderArray[orderNumber] = theOrder;
function orderUpdate(item,price){
theOrder = [item, price];
orderArray.push(theOrder);
// orderNumber++;
}
jsfiddle https://jsfiddle.net/purnrntr/2/

Append an Array to an Unordered List

What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
document.write('<li>' + alphabet[indexNum++] + '</li>');
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
Don't use document.write to do it. You should act like this:
function write_letters(){
var letters = "";
for (var i = 0; i < alphabet.length; i++ ) {
//Also I don't understand the purpose of the indexNum variable.
//letters += "<li>" + alphabet[indexNum++] + "</li>";
letters += "<li>" + alphabet[i] + "</li>";
}
document.getElementById("itemList").innerHTML = letters;
}
More proper way is to use DOM (in case you want full control of what's coming on):
function write_letters(){
var items = document.getElementById("itemList");
for (var i = 0; i < alphabet.length; i++ ) {
var item = document.createElement("li");
item.innerHTML = alphabet[i];
items.appendChild(item);
}
}
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
<html>
<head>
<title>Script Test</title>
</head>
<body>
<ul id="itemList"></ul>
</body>
<script>
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var myElement;
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
// Create the <LI> element
myElement = document.createElement("LI");
// Add the letter between the <LI> tags
myElement.innerHTML = alphabet[indexNum++];
// Append the <LI> to the bottom of the <UL> element
unorderedList.appendChild(myElement);
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
</script>
</html>
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
Try to reduce the actions on the DOM as much as possible. Every appendChild on unorderedList forces the browser to re-render the complete page. Use documentFragement for that sort of action.
var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(alphabet[indexNum++]));
frag.appendChild(li);
}
unorderedList.appendChild(frag);
So there will be only one DOM action which forces a complete redraw instead of alphabet.length redraws

Categories

Resources