Datatable return from select

0

I am using the datatable with ajax, getting among others a column with select, but I do not know why onchange does not work. Here's the ajax return:

{"data":
  [[
    1,
    "17020161",
    "Marina Costa Vasconcelos",
    "<select data-id='17020161' id='status_aluno17020161' style='background-color: #00C851; color:white' class='form-control status' ><option style='background-color: #00C851; color:white' value='1' >Presente<\/option>\n<option style='background-color: #ff4444; color:white' value='2'>Falta<\/option><\/select>",
    "",
    "",
    ""
  ],[
    2,
    "12080243",
    "Talita de Souza Menezes",
    "<select data-id='12080243' id='status_aluno12080243' style='background-color: #00C851; color:white' class='form-control status' ><option style='background-color: #00C851; color:white' value='1' >Presente<\/option>\n<option style='background-color: #ff4444; color:white' value='2'>Falta<\/option><\/select>",
    "",
    "",
    ""
  ]]
}

In this the following function does not work:

$(document).ready(function() {  
    $('.status').on('change', function() {
        //$(".status").change(function(){
            var valor = this.value;
            var matricula = $(this).data("id");
            alert(matricula);
            alert(valor);

            if (valor == 1) { 
                $("#status_aluno"+matricula).css("background-color", "#00C851"); 
            } 
            if (valor == 2) { 
                    $("#status_aluno"+matricula).css("background-color", "#ff4444");
            }
            if (valor == 3) { 
                    $("#status_aluno"+matricula).css("background-color", "#00C851"); 
            } 
            if (valor == 4) { 
                    $("#status_aluno"+matricula).css("background-color", "#ffbb33"); 
            }
            if (valor == 5) { 
                    $("#status_aluno"+matricula).css("background-color", "#ffbb33"); 
            }
            if (valor == 6) { 
                    $("#status_aluno"+matricula).css("background-color", "#ff4444"); 
            }
        }
    );
});
    
asked by anonymous 13.11.2017 / 19:04

1 answer

0

It does not work because you are not adding the function to your select because this javascript runs before it exists in the document.

The way this would work would be by using delegated events. You add the event handler to the parent element, and use a selector to designate when it will fire. It would look something like this:

$(document).on('change', '.status', function() {
   // aqui mantém tudo
}

Here I add the event in document , but it will only fire when the '.status' selector is found, and works even for added elements after attaching the event to document . Another detail, it would be even more interesting to add in <form> , instead of document , where this <select> will be.

More information

link

    
13.11.2017 / 19:20