How can I insert a script in a string?

1

I want to create tabs from some data consulted in the database, in each tab you will have checkbox which I want to have an action onChange but I can not insert the tag script in a chain string

function GenerarPestanias() {
        var pestanias = '<ul class="nav nav-tabs" role="tablist">';
        $.each( todoFunciones, function( i, j ){
            if(i!=0){
                if(j.id_padre==0){
                    var ident = j.titulo.toLowerCase().replace(/\s/g,'');

                    $.each( todoFunciones, function( x, y ){
                        if(y.id_padre==j.id){
                        }
                    });
                    pestanias += ''+
                    '<li><a href="#'+ident+'" data-toggle="tab" aria-expanded="true">'+j.titulo+' '+
                    '<input id="menu_'+ident+'" name="menu_'+ident+'" data-info="general" name="my-checkbox" type="checkbox"  data-toggle="toggle" data-on="<span class=\'fa fa-power-off\'></span>" data-off="<span class=\'fa fa-power-off\'></span>" data-onstyle="success" data-offstyle="danger">'+
                    '</a>'+
                    '</li>'+
                    '<script type="text/javascript">'+
                    '</script>';
                }
            }
        });
        pestanias += '</ul>';
        return pestanias;
    }

At the end of the script tag it throws me an error.

I do not know if it is the right way, if there is another and better, welcome it will be.

Update 1:

I would like each checkbox to contain something like this:

    $('#checkbox').on("change", function(){
        if($(this).prop("checked") == true){
             alert(true);
        }else{
             alert(false);
        }
    });

Update 2:

Do not explain what I want each checkbox to do, because as I said above I create tabs with bootstrap ( as here ) From a query to the BD, the table is composed as follows:


CREATE TABLE public.funciones
(
  id integer NOT NULL DEFAULT nextval('funciones_id_seq'::regclass),
  id_padre integer NOT NULL,
  icono character varying(255) NOT NULL,
  link character varying(255) NOT NULL,
  titulo character varying(255) NOT NULL,
  status boolean NOT NULL
)

Those that contain id_padres = 0 are the tabs, those that contain id_padres > 0 are children which I want to appear within the content of each tab as well as checkbox.

Here is an example of a query (typo json) to the table



todoFunciones = 
            [
            {
              "id": 1,
              "id_padre": 0,
              "icono": "fa fa-dashboard fa-fw",
              "link": "/",
              "titulo": "Tablero",
              "status": true
          },
          {
              "id": 2,
              "id_padre": 0,
              "icono": "fa fa-tasks fa-fw",
              "link": "#",
              "titulo": "Procesos",
              "status": true
          },
          {
              "id": 3,
              "id_padre": 2,
              "icono": "fa fa-list-ol fa-fw",
              "link": "/lotes",
              "titulo": "Lotes",
              "status": true
          },
          {
              "id": 4,
              "id_padre": 2,
              "icono": "fa fa-eraser fa-fw",
              "link": "/limpieza",
              "titulo": "Limpieza",
              "status": true
          },
          {
              "id": 5,
              "id_padre": 2,
              "icono": "fa fa-stop fa-fw",
              "link": "/paradas",
              "titulo": "Paradas",
              "status": true
          },
          {
              "id": 6,
              "id_padre": 2,
              "icono": "fa fa-wrench fa-fw",
              "link": "#",
              "titulo": "Mantenimiento",
              "status": true
          }
          ]
          ;

    
asked by Pablo Contreras 19.12.2016 в 23:14
source

3 answers

1

And because you do not simply create a onChange for the class of your inputs:

$(document).ready(function(){

  $('.checkbox').bind('change', function() {
    /*if($(this).prop("checked") == true){
      alert(true);
    }else{
      alert(false);
    }*/
    if($(this).data("tipo")=="tipo1"){
      alert("tipo 1");
    }else if($(this).data("tipo")=="tipo2"){
      alert("tipo 2");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" data-tipo="tipo1">
<input type="checkbox" class="checkbox" data-tipo="tipo2">
    
answered by 20.12.2016 в 00:26
0

Since it seems that checkboxes are created dynamically with JavaScript / jQuery, what you can do is associate delegated events that will be associated with the elements as soon as they are created and added to the DOM.

You can read more about delegated events in the jQuery documentation for .on() ( in English). Where it is explained (my translation):

  

Delegated events have the advantage that they can process descendant events that have been added to the document at a later time. By selecting an element that is guaranteed to be present at the time the delegate event handler is associated, it is possible to delegate events to avoid the need to associate and remove event handlers frequently. This element should be the container element of a view in the Model-View-Controller design, for example, or document if the evneto controller wants to monitor all the events that arise in the document. The document element is available in the head of the document before loading any HTML, so it is safest to associate events without having to wait for the document to be ready.

So the format of the association would be something like this (for example for the click):

$( "selector-de-un-ancestro" ).on( "click", "selector-del-elemento-objetivo", function() {
   // acciones a ejectura al hacer click
});

In your particular case, what you would do is leave the code exactly as you have it and out of the link make the association of delegated events. Knowing that an ancestor will be the body you could do something like this:

  

Note that the higher / higher the ancestor, the less efficient the association will be; It is advisable to make the ancestor as concrete as possible.

$("body").on("click", "input[type='checkbox']", function() {
  if($(this).prop("checked") == true){
    alert(true);
  }else{
    alert(false);
  }
});

function GenerarPestanias() {
  var pestanias = '<ul class="nav nav-tabs" role="tablist">';
  $.each( todoFunciones, function( i, j ){
    if(i!=0){
      if(j.id_padre==0){
        var ident = j.titulo.toLowerCase().replace(/\s/g,'');

        $.each( todoFunciones, function( x, y ){
          if(y.id_padre==j.id){
          }
        });
        pestanias += ''+
          '<li><a href="#'+ident+'" data-toggle="tab" aria-expanded="true">'+j.titulo+' '+
          '<input id="menu_'+ident+'" name="menu_'+ident+'" data-info="general" name="my-checkbox" type="checkbox"  data-toggle="toggle" data-on="<span class=\'fa fa-power-off\'></span>" data-off="<span class=\'fa fa-power-off\'></span>" data-onstyle="success" data-offstyle="danger">'+
          '</a>'+
          '</li>'; // eliminé las etiquetas script
      }
    }
  });
  pestanias += '</ul>';
  return pestanias;
}
    
answered by 20.12.2016 в 02:49
0

If what you want is to generate a few tabs using the information of a database and that each tab contains a checkbox with a eventListener each, then here is an example, I did not give styles to the checkbox.

Here is the HTML:     

        <!-- Nav tabs -->
        <ul id="pestañas" class="nav nav-tabs" role="tablist">
            <!--<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
            <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
            <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
            <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>-->
        </ul>

        <!-- Tab panes -->
        <div id="contenido" class="tab-content">
           <!-- <div role="tabpanel" class="tab-pane active" id="home">Home</div>
            <div role="tabpanel" class="tab-pane" id="profile">Profile</div>
            <div role="tabpanel" class="tab-pane" id="messages">Messages</div>
            <div role="tabpanel" class="tab-pane" id="settings">Settings</div>-->
        </div>

    </div>

This is the JSON that you use:

[{
                "id": 1,
                "id_padre": 0,
                "status": true,
                "link": "#home",
                "titulo": "Home"
            },
            {
                "id": 2,
                "id_padre": 0,
                "status": true,
                "link": "#profile",
                "titulo": "Profile"
            },
            {
                "id": 3,
                "id_padre": 0,
                "status": true,
                "link": "#messages",
                "titulo": "Messages"
            }]

The javascript:

var pestañas = document.querySelector('#pestañas'),
            contenido = document.querySelector('#contenido'),
            primera = true,
            tf = [{
                "id": 1,
                "id_padre": 0,
                "status": true,
                "link": "#home",
                "titulo": "Home"
            },
            {
                "id": 2,
                "id_padre": 0,
                "status": true,
                "link": "#profile",
                "titulo": "Profile"
            },
            {
                "id": 3,
                "id_padre": 0,
                "status": true,
                "link": "#messages",
                "titulo": "Messages"
            }];

        function generarPestañas(callback){
            for(var i=0, objeto; objeto=tf[i]; i++){
                if(objeto.id_padre == 0){
                    var pestaña_actual = generarPestaña(primera, objeto.link, objeto.titulo, function(){
                        if(this.checked == true){
                            alert('true');
                        }
                        else{
                            alert('false');
                        }
                    });
                    pestañas.appendChild( pestaña_actual );
                    primera = false;
                }
            }
            callback();
        }
        //generarPestañas();
        function generarPestaña(_primera, link, titulo, callback){
            var pestaña = document.createElement('li'),
                enlace = document.createElement('a'),
                checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            pestaña.setAttribute('role', 'presentation');
            enlace.textContent = titulo;
            enlace.setAttribute('href', link);
            enlace.setAttribute('role', 'tab');
            enlace.setAttribute('data-toggle', 'tab');
            if(_primera == true){
                pestaña.setAttribute('class', 'active');
            }
            pestaña.appendChild( enlace );
            pestaña.appendChild( checkbox );
            checkbox.addEventListener('change', function(){
                callback.call( this );
            }, false);
            return pestaña;
        }
        function iniciarPestañas(){
            generarPestañas(function(){
                $('li[role=presentation] a').click(function(e){
                    e.preventDefault();
                    $(this).tab('show');
                });
            });
        }
        iniciarPestañas();
    
answered by 20.12.2016 в 18:17