Check checkbox with ajax

Asked

Viewed 1,314 times

1

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

Can someone help me ? Follow my function (I call her in 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>';
}
  • 1

    What is the id? You can show how it is in HTML?

  • Hi @Sergio, I put html in the question.

  • Okay, I added more details to my answer

4 answers

5

I suggest running this function by Javascript and not inline by HTML.

That way you have access to the element that was clicked and easily read the state 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: https://jsfiddle.net/a8dpwg5w/

updating:

With the HTML you have now added to the question I suggest so, 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 of HTML.

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 his job check_cadmanual:

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

2


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

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

See if it helps.

  • the is(':checked')) did exactly what I needed, didn’t even need to change anything else.. Super thank you !!!

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 their resources to make your life easier and accelerate your development.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.