VictorRee
VictorRee

Reputation: 3

Button creation Function code error unable to locate

Am to new site, I have tried looking for an answer but been unable (if anyone knows location of post that can help its appreciated) on to problem ...

I am trying to create a button system which will add new buttons dependent on info in an array, i keep getting new info to put in so figured would speed up input and update.

 <!DOCTYPE html>
 <html>
 <head>
   <title> Function Test </title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
   <script>

    var textNum = ["<b>O</b>ne", "<b>T</b>wo", "three", "four", "five"];
    var i;
    var build = "";
    function callText(a) {

            document.getElementById("demo").innerHTML = textNum[a];
    }

    </script>   
   </head>

    <body>
      <button onclick = "callText(0)"> 1 </button>
      <button onclick = "callText(1)"> 2 </button>
      <button onclick = "callText(2)"> 3 </button>
      <button onclick = "callText(3)"> 4 </button>
      <button onclick = "callText(4)"> 5 </button>
      <p id="demo"></p>

      <br>
      <br>
      <p id="createbutton"></p>
      <p id="displayHere"></p>
    <script>
      var newText =[1, 2];
      var i;
      var build = "";
      function display(a) {
           document.getElementById("displayHere").innerHTML = newText[a];
       };


      for (i = 0; i < newText.length; i++) {

            build +="<button onclick = \\display(i)\\>" + newText[i] + "</button>" ;
        };
        document.getElementById("createbutton").innerHTML = build;
      </script>

   </body>
      </html>

Uncaught SyntaxError: Unexpected token ILLEGAL function test.html:46

(its highlighting the > on the final /script)

it creates the buttons, but comes up with that error any ideas

Upvotes: 0

Views: 42

Answers (2)

jlowcs
jlowcs

Reputation: 1933

2 issues with your code:

1) What's with the "\\display(i)\\"? What were you trying to do?

2) You can't use "i" in the generated HTML here. You need to insert the value of i

For instance:

build += "<button onclick=\"display(" + i + ")\">" + newText[i] + "</button>" ;

Upvotes: 1

Poul Bak
Poul Bak

Reputation: 10929

build will contain "button onclick=\display(i)...

You want to put the onclick handler inside quotes, like this:

build +="<button onclick = 'display(i)'>" + newText[i] + "</button>" ;

Upvotes: 0

Related Questions