Checkbox checkbox with ajax

1

I have a checkbox that when checked or unchecked performs an update in the database, with ajax. But I do not know how to analyze his state change event. If you use checked it considers only the current state of the button.

Can anyone help me? Here's my function (I call it on the checkbox onchange):

function check_cadmanual(id){
    var id_pronto = id.split("_");
    var codveiculo = id_pronto[1];
    event.preventDefault();
    if(document.frmveic.iptcadastromanual.checked) {
        document.frmveic.funcao.value = "ativo";
    } else {
        document.frmveic.funcao.value = "inativo";
    }
    startloader();
    var jqxhr = $.ajax( {
        url: "/configuracao_veiculo",
        type: "POST",
        data: {
            timeout:default_timeout,
            iptcadastromanual:codveiculo,
            funcao: document.frmveic.funcao.value

        }
    })
    .done(function() {
        stoploader();
        ajaxget('veiculo', 'Veículos');
        if(document.frmveic.funcao.value == "ativo") {
            mensagemSucesso("Esse veículo já pode ser acessado no cadastro manual de clientes !");
        } else {
            mensagemValidacao("Atenção","Esse veículo não está mais disponível no cadastro manual de clientes !");
        }
    });
}

The assembly of the checkbox:

$sql = "select codveiculo, nome, indcadastromanual from veiculo 
            where codempresa=".$codempresa." order by nome";
$rst = my_query($connR, $sql);
foreach($rst as &$row){
    if($row['indcadastromanual'] == 1) {
        $checked = "checked='checked'";
    } elseif ($row['indcadastromanual'] == 0) {
        $checked = " ";
    }
    $htmlveiculo='<ul>';
    $htmlveiculo .="<input type='checkbox' name='iptcadastromanual' class='onoffswitch-checkbox' id='iptcadastromanual_".$row['codveiculo']."' onchange='javascript:check_cadmanual(this.id);' ".$checked." >"
    $htmlveiculo .= '</ul>';
}
    
asked by anonymous 23.12.2015 / 13:50

4 answers

2

Place a change event in your checkbox, and check whether or not it is checked with the command $('#myCheckbox').is(':checked')

  //Exemplo
  $('#myCheck').bind('change',function(){
    alert('Checkbox checado?'+ $(this).is(':checked'));
    //Seu ajax aqui
  })

See if it helps.

    
23.12.2015 / 14:04
5

I suggest you run this function through JavaScript and not inline through HTML.

This way you have access to the element that was clicked and easily read the status with this.checked .

Example:

var checkbox = document.querySelector('input');
checkbox.addEventListener('change', check_cadmanual)
function check_cadmanual() {
    document.getElementById('res').innerHTML = this.checked ? 'marcado' : 'desmarcado';
}
Clica aqui -> <input type="checkbox">
<div id="res"></div>

jsfiddle: link

update:

With the HTML that you put together now to the question I suggest then, use the code like this:

$('.onoffswitch-checkbox').on('change', check_cadmanual);

function check_cadmanual() {
    var id = this.id;
    var checked = this.checked
    // e o resto igual, e para saberes o estado tens agora uma variavel com essa informação

Removing this onchange from HTML.

    
23.12.2015 / 14:07
4

Assuming you have the following checkbox :

<input type="checkbox" id="checkVeiculo" value="" />

You can assign an onclick event via javascript:

<input type="checkbox" id="checkVeiculo" value="" onclick="javascript:check_cadmanual(this)"/>

In your role check_cadmanual :

function check_cadmanual(elemento) {
    var checkbox = $(elemento);
    var checked = checkbox.prop("checked");
    if (checked) {
      // seu ajax.
    } else {
      // TODO
    }    
}
    
23.12.2015 / 14:07
2

I would do something like this:

<input type="checkbox" id="idDoCheckbox" data-id="idDoVeiculo" />

$(function() {
    $("#idDoCheckBox").click(function() {
        startLoader();
        var checked = this.checked;
        var funcao = checked ? "ativo" : "inativo";
        var id = $(this).attr("data-id");

        // suas chamadas ajax...
    });
});

Try not to mix too much jQuery with pure JavaScript. There's no problem with that, but if you're already implementing jQuery, use all of its features to make life easier and accelerate.

    
23.12.2015 / 14:07