0

I have this function that spawns a group of elements inside an ordered list when a button is clicked, all elements in a spawned group have the same id/timestamp. the function works fine up until an "if" statement where I validate/create/push an array of ID's. I do not understand why it will not execute.

This is my JS function, sorry about the length:

function spawnSilly() //spawn chapters function
        {
            const timestamp = new Date().getUTCMilliseconds();

            var div = document.createElement("LI"); //creating elements
            var input = document.createElement("INPUT");
            var button = document.createElement("BUTTON");
            var del_button = document.createElement("BUTTON")
            input.setAttribute("type", "text");     //setting attributes
            input.setAttribute("placeholder", "Title");
            input.setAttribute("id", timestamp.toString())
            button.setAttribute("type", "button");
            button.setAttribute("onClick", "redirect()");
            button.setAttribute("id", timestamp.toString())
            button.innerHTML = "Edit";
            div.setAttribute("id", timestamp.toString())
            del_button.setAttribute("id", timestamp.toString())
            del_button.innerHTML = "Delete Chapter";
            del_button.setAttribute("onClick", "removeElement(this.id)")
            div.appendChild(input)      //appending to list
            div.appendChild(button)
            div.appendChild(del_button);
            var chapterNumber = getCount(document.getElementById('spawnList'), false) //setting number of spawn
            var number = $('#spawnList').children(); //fetching number of children in list
             //setting chapter number to string for name attribute in input
            var list = document.getElementById("spawnList")
            list.insertBefore(div, list.childNodes[number]) //inserting one after another
            var newSpawnNumber = string(number + 1);  //setting elements class as their spawn number
            input.setAttribute("class", newSpawnNumber)
            button.setAttribute("class", newSpawnNumber)
            div.setAttribute("class", newSpawnNumber)
            del_button.setAttribute("class", newSpawnNumber)
            input.setAttribute("index", newSpawnNumber)
            button.setAttribute("index", newSpawnNumber)
            div.setAttribute("index", newSpawnNumber)
            del_button.setAttribute("index", newSpawnNumber)
            if (typeof idArray !== "undefined")
                {
                    idArray.push("#" + new Date().getUTCMilliseconds().toString())
                    alert("push success")
                }
            else if (typeof idArray == "undefined")
                {
                    idArray = new Array()
                    idArray.push("#" + new Date().getUTCMilliseconds().toString())
                    alert("created new array, push success")
                }
            else
                {
                    alert("error")
                }
            alert("success")
        }

    </script>

If I place an alert just preceding the if statement it executes, however if i place it after the if statement it does not execute, strange.

This is my HTML:

<a href="#" onclick="alert(getCount(document.getElementById('spawnList'), false));">Count Spawn</a><br/>
<form action="spawn-title-processing.php" method="post">
  <ol id="spawnList">


  </ol>
  <button type="button" id="spawnbtn" onClick="spawnSilly();">Add </button>
  <button type="button" name="spawnSubmit" onClick="submit_chpt">Save</button>
</form>

These are the console errors:

    Uncaught ReferenceError: string is not defined
    at spawnSilly (post_creation.php:162)
    at HTMLButtonElement.onclick (VM786 post_creation.php:197)
spawnSilly @ post_creation.php:162
onclick @ VM786 post_creation.php:197

Any help would be fantastic! :)

6
  • It would be helpful to see where idArray is initialized (and that it is initialized). It's possible that it is initialized to something other than an array and so it is !== undefined and an error is thrown when attempting to push() onto the array. Commented Apr 22, 2019 at 4:12
  • idArray is initialized through the first spawning of a group of elements, via the first iteration of the if statement. so it should be undefined if no groups have been spawned, but none of the if statement executes. I've also tried initializing idArray as an array just preceding the if statement, and it doesn't seem to work :( Commented Apr 22, 2019 at 4:16
  • Correct your idArray initialization var idArray = new Array() Commented Apr 22, 2019 at 4:16
  • it initializes upon the first spawn, initializing it with each spawn would defeat the purpose Commented Apr 22, 2019 at 4:20
  • @akemedis then define your idArray Outside the function. Commented Apr 22, 2019 at 4:25

3 Answers 3

1

you are checking your if condition undefined in a wrong way. you need to change the following lines.

from

 if (idArray !== undefined) {

to

if (typeof idArray !== "undefined") {

from

} else if (idArray == undefined) {

to

} else if (typeof idArray == "undefined") {

Updated:

you need to also change this line

from

idArray.push("#" + string(new Date().getUTCMilliseconds()))

to

idArray.push("#" + new Date().getUTCMilliseconds().toString())

function spawnSilly() //spawn chapters function
{

  var div = document.createElement("LI"); //creating elements
  var input = document.createElement("INPUT");
  var button = document.createElement("BUTTON");
  var del_button = document.createElement("BUTTON")
  input.setAttribute("type", "text"); //setting attributes
  input.setAttribute("placeholder", "Title");
  input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
  button.setAttribute("type", "button");
  button.setAttribute("onClick", "redirect()");
  button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
  button.innerHTML = "Edit";
  div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
  del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
  del_button.innerHTML = "Delete Chapter";
  del_button.setAttribute("onClick", "removeElement(this.id)")
  div.appendChild(input) //appending to list
  div.appendChild(button)
  div.appendChild(del_button);
  var spawnNumber = 10;
  //getCount(document.getElementById('spawnList'), false) //setting number of spawn
  var number = $('#spawnList').children(); //fetching number of children in list
  var stringNumber = String(number) //setting spawn number to string for name attribute in input
  var list = document.getElementById("spawnList")
  list.insertBefore(div, list.childNodes[number]) //inserting one after another
  var newSpawnNumber = spawnNumber + 1; //setting elements class as their spawn number
  input.setAttribute("class", newSpawnNumber)
  button.setAttribute("class", newSpawnNumber)
  div.setAttribute("class", newSpawnNumber)
  del_button.setAttribute("class", newSpawnNumber)
  input.setAttribute("index", newSpawnNumber)
  button.setAttribute("index", newSpawnNumber)
  div.setAttribute("index", newSpawnNumber)
  del_button.setAttribute("index", newSpawnNumber)
  if (typeof idArray !== "undefined") {
    idArray.push("#" + new Date().getUTCMilliseconds().toString())
    alert("push success")
  } else if (typeof idArray == "undefined") {
    idArray = new Array()
    idArray.push("#" + new Date().getUTCMilliseconds().toString())
    alert("created new aray, push success")
  } else {
    alert("error")
  }
  alert("success")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" onclick="alert(getCount(document.getElementById('spawnList'), false));">Count Spawn</a><br/>
<form action="spawn-title-processing.php" method="post">
  <ol id="spawnList">


  </ol>
  <button type="button" id="spawnbtn" onClick="spawnSilly();">Add </button>
  <button type="button" name="spawnSubmit" onClick="submit_chpt">Save</button>
</form>

Sign up to request clarification or add additional context in comments.

4 Comments

the error you added in question in in another function getCount() which you didn't add in your questoin
Updated, the error is pointing to the button.innerHTML command, however when i delete that command, it still throws up the error to line 103, ie. an empty line because i deleted button.innerHTML, very confused
I want mine to work like that so bad, I've updated my question, it throws up the string error again, i can delete half the function and it will still throw up a random string error on seemingly random lines, i deleted half the function as a test, and it threw up a string error on a blank line outside of the function, i have no idea whats going on
I copied your code and it worked, confused but im happy to go with it, Thankyou for the help :)
0

Your idArray in the if statement is not defined, which must be causing error and thats where the program to stop.

For advise, it is better to make your code clean.

For example,

//spawn chapters function
function spawnSilly() {
  const timestamp = new Date().getUTCMilliseconds();

  var li = document.createElement("LI"); 
  li.setAttribute("id", timestamp)

  var input = document.createElement("INPUT");
  input.setAttribute("type", "text");
  input.setAttribute("placeholder", "Title");
  input.setAttribute("id", timestamp)

  var button = document.createElement("BUTTON");
  button.setAttribute("type", "button");
  button.setAttribute("onClick", "redirect()");
  button.setAttribute("id", timestamp)
  button.innerHTML = "Edit";

  var del_button = document.createElement("BUTTON")
  del_button.setAttribute("id", timestamp)
  del_button.setAttribute("onClick", "removeElement(this.id)")
  del_button.innerHTML = "Delete Chapter";

  //appending to list
  li.appendChild(input)
  li.appendChild(button)
  li.appendChild(del_button);

  // and so on...
}

1 Comment

I have defined it inside, and outside the function to no avail :(
0
window.cn = function(o) { return"undefined" == typeof o || null == o || "" == o.toString().trim()}

after that u check your variable like this

window.cn(idArray)

if value is not in idArray then it return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.