-2

I'm trying to make new element using createElement method. But in this case I want id attribute should change as variable changes while adding Dynamic Input using Button.

Uncaught SyntaxError: Unexpected identifier

Here, I'm using \n for new line for formating input in createElement method.

Below code was working If I remove script tag. But in this case I want script tag for using select2.

var personCount = 1;

function addNewInput(divName){
    var newdiv = document.createElement('div');
    newdiv.innerHTML = '<select style="width: 100%" id="person'+ (personCount + 1) +'"StateInput" ></select>\n\
                        <script>\n\
                          $('#person'+ (personCount + 1) +'"StateInput').select2({\n\
                              ajax: {\n\
                                url: 'url/for/state',\n\
                                dataType: 'json'\n\
                              }\n\
                            });\n\
                        </script>';
  
    document.getElementById(divName).appendChild(newdiv);
    count++;
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
  

    <select style="width: 100%" id="person1StateInput" ></select>
    <script>
      $('#Test1A').select2({
          ajax: {
            url: 'url/state',
            dataType: 'json'
          }
        });
    </script>

<div id="add"></div>

<button class="btn btn-primary" onclick="addNewInput('add');">Add Peaky Blinder</button>

The code will explain the problem better rather than a description

Maqsud
  • 739
  • 3
  • 12
  • 35
  • 1
    Apart from the syntax error due to incorrect quoting, and potentially from the fact that `` terminates the script, inserting a script in `innerHTML` will not work. Why not simply call a function with the JS code? – Sebastian Simon Jan 23 '21 at 14:43
  • 1
    Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_—_dont_use_these) or jQuery’s [`.on`](https://api.jquery.com/on/) instead. – Sebastian Simon Jan 23 '21 at 14:46
  • 2
    This is not the right approach. If you intend to add new `select` menus (&other html) dynamically you might be better assigning an event handler to the parent node ( this node that you add the new content to ) and use `event delegation` to find what the event was, what triggered it and then react accordingly. Certainly no need to add a new function for each select menu – Professor Abronsius Jan 23 '21 at 14:46
  • What do you do with the ajax response? – Professor Abronsius Jan 23 '21 at 14:55
  • @ProfessorAbronsius This is just example for using script in `innerHTML`. – Maqsud Jan 23 '21 at 14:56
  • @SebastianSimon, Can help with Syntax Error using script in `createElement` method. – Maqsud Jan 23 '21 at 14:58
  • ok so the ajax call is not important? As for the error message - why not just insert a new HTML element from scratch rather than a string? – Professor Abronsius Jan 23 '21 at 14:59
  • @ProfessorAbronsius, Yes that AJAX is not important. Yes inserting new HTML is required but inserting `script` is required. – Maqsud Jan 23 '21 at 15:01
  • @Maqsud _“inserting `script` is required”_ — No, it is not, because this will never work. Again, why can’t you just put that script code in a function and call it? – Sebastian Simon Jan 23 '21 at 15:06
  • @SebastianSimon, Can you show me the solution to this problem. – Maqsud Jan 23 '21 at 15:13
  • @Maqsud Please see a [tutorial on how to declare and use functions](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions). – Sebastian Simon Jan 23 '21 at 15:16

2 Answers2

1

It is a little unclear what the real objective ultimately is but you said you need to insert new HTML elements and new scripts( why though ? ) ~ you can use createElement to create all of these things, including new scripts. The following is loosely based upon the code you provided - a new Select will be created in the #add div and anew script element will also be added - though it is of limited use "as-is"

var personCount = 1;

const addPeakyBlinder=function(divName){
  let oSelect=document.createElement('select');
    oSelect.id='person'+personCount;
    oSelect.style.width='100%';
    /* below for demo only */
    oSelect.appendChild(new Option('apple','apple'));
    oSelect.appendChild(new Option('banana','banana'));
    oSelect.appendChild(new Option('peach','peach'));

  let oScript=document.createElement('script');
    oScript.textContent=`
      console.log('loaded');
    `;

  let oDiv=document.createElement('div');   
    oDiv.appendChild(oSelect);
    oDiv.appendChild(oScript)



  document.getElementById( divName ).appendChild( oDiv );
  personCount++;
}


document.getElementById( 'add' ).addEventListener('change',e=>{
  console.info( 'Do interesting things.. now we know the origin for the request and the value: %s %s %s %s', e.type, e.target, e.target.value, e.target.id )
});
<div id="add"></div>
<button onclick="addPeakyBlinder('add');">Add Peaky Blinder</button>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1

I just modified the answer of @ProfessorAbronsius which is the exact solution I wanted.

var personCount = 1;

const addPeakyBlinder=function(divName){
  let oSelect=document.createElement('select');
    oSelect.style.width='100%';
    oSelect.setAttribute("id", "Test"+ (personCount + 1) +"A");

  let oScript=document.createElement('script');
    oScript.textContent=`
       $("#Test`+ (personCount + 1) +`A").select2({\n\
          ajax: {\n\
            url: 'https://api.github.com/search/repositories',\n\
            dataType: 'json'\n\
          }\n\
        });\n\
    `;

  let oDiv=document.createElement('div');   
    oDiv.appendChild(oSelect);
    oDiv.appendChild(oScript)

personCount++

  document.getElementById( divName ).appendChild( oDiv );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
  

    <select style="width: 100%" id="Test1A" ></select>
    <script>
      $('#Test1A').select2({
          ajax: {
            url: 'url/state',
            dataType: 'json'
          }
        });
    </script>

<div id="add"></div>

<button class="btn btn-primary" onclick="addPeakyBlinder('add');">Add Peaky Blinder</button>
Maqsud
  • 739
  • 3
  • 12
  • 35