Force to fill checkbox whenever you register a task

Asked

Viewed 126 times

1

I have the following form to record tasks. I record tasks separately.

Code:

<div class="form-group">
<div>
<label for="Indicar">Comeu Bem: </label>
<label for="Notas"> Sim</label>
<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
<label for="check1"> Não</label>
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required />
</div>
<input type="hidden" id="tarefa18" name="tarefa" value="30">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Pequeno Almoço</button><button type="button" name="abrir18"><span class="glyphicon glyphicon-comment"></span></button>
<div class="form-group" id="comentario18" style="display:none">
<textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>
</div>
</div>
</div>

Ajax to insert:

function inserir_registo18()
{

    var dadosajax = {
        'tarefa' : $("#tarefa18").val(),
        'Notas' : $("#Notas11").val(),
        'Notas' : $("#Notas12").val(),
        'Observacao' : $("#Observacao18").val()
    };
    $.ajax({
        url: './insertarefa1',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        { 
        }
    });
}

I intend that whenever you perform this action onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;" check that one of the checkboxes is filled, if it is not filled in, do not perform the action and force one of the checkboxes to be filled in.

I was trying to:

function inserir_registo18()
    {
        var checado = $("#Notas11").is(':checked')
        var checado1 = $("#Notas12").is(':checked')
        if(checado == true || checado1 == true){
        var dadosajax = {
            'tarefa' : $("#tarefa18").val(),
            'Notas' : $("#Notas11").val(),
            'Notas' : $("#Notas12").val(),
            'Observacao' : $("#Observacao18").val()
        };
        $.ajax({
            url: './insertarefa1',
            type: 'POST',
            cache: false,
            data: dadosajax,
            error: function(){

            },
            success: function(result)
            { 
            }
        });
       }
    }

Question edition:

Example:

<div class="form-group">
<div>
<label for="Indicar">Comeu Bem: </label>
<label for="Notas"> Sim</label>
<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
<label for="check1"> Não</label>
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required />
</div>
<input type="hidden" id="tarefa18" name="tarefa" value="30">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Pequeno Almoço</button><button type="button" name="abrir18"><span class="glyphicon glyphicon-comment"></span></button>
<div class="form-group" id="comentario18" style="display:none">
<textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>
</div>
</div>

<div class="form-group">
<div>
<label for="Indicar">Comeu Bem: </label>
<label for="Notas"> Sim</label>
<input type="checkbox" name="Notas" id="Notas" Value="Sim" required />
<label for="check1"> Não</label>
<input type="checkbox" name="Notas" id="Notas1" Value="Não" required />
</div>
<input type="hidden" id="tarefa19" name="tarefa" value="31">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo19();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Almoço</button><button type="button" name="abrir19"><span class="glyphicon glyphicon-comment"></span></button>
<div class="form-group" id="comentario19" style="display:none">
<textarea id="Observacao19" name="Observacao" style="color: black;"></textarea>
</div>
</div>

<div class="form-group">
<div>
<label for="Indicar">Comeu Bem: </label>
<label for="Notas"> Sim</label>
<input type="checkbox" name="Notas" id="Notas2" Value="Sim" required />
<label for="check1"> Não</label>
<input type="checkbox" name="Notas" id="Notas3" Value="Não" required />
</div>
<input type="hidden" id="tarefa20" name="tarefa" value="32">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo20();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Lanche</button><button type="button" name="abrir20"><span class="glyphicon glyphicon-comment"></span></button>
<div class="form-group" id="comentario20" style="display:none">
<textarea id="Observacao20" name="Observacao" style="color: black;"></textarea>
</div>
</div>

javascript:

function inserir_registo18()
{
    var checado = $("#Notas11").is(':checked')
    var checado1 = $("#Notas12").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{   
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa18").val(),
        'Notas11' : $("#Notas11").is(":checked") ? $("#Notas11").val() : '',
        'Notas12' : $("#Notas12").is(":checked") ? $("#Notas12").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao18").val()
    };  
    $.ajax({
        url: './insertarefa4',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        { 
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
}else {
      alert('Selecione um campo');
    }

}
}
function inserir_registo19()
{
    var checado = $("#Notas").is(':checked')
    var checado1 = $("#Notas1").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{   
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa19").val(),
        'Notas' : $("#Notas").is(":checked") ? $("#Notas").val() : '',
        'Notas1' : $("#Notas1").is(":checked") ? $("#Notas1").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao19").val()
    };
    $.ajax({
        url: './insertarefa5',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        { 
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
    }else {
      alert('Selecione um campo');
    }
}
}
function inserir_registo20()
{ 
    var checado = $("#Notas2").is(':checked')
    var checado1 = $("#Notas3").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{   
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa20").val(),
        'Notas2' : $("#Notas2").is(":checked") ? $("#Notas2").val() : '',
        'Notas3' : $("#Notas3").is(":checked") ? $("#Notas3").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao20").val()
    };
    $.ajax({
        url: './insertarefa6',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        { 
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
    }else {
      alert('Selecione um campo');
    }
}
} 
  • What a mistake you’re making friend?

  • You’re trying with an id that doesn’t exist...

  • @Maycon F. Castro, is not giving error, and does not register in the database, but the user gets the idea that he has registered in the database, and should not end the process of locking the button until the checkbox is filled

  • @Darlei Fernando Zillmer already changed the ids, so does not register, but intended that when clicking the button to enter, if it checked that none of the checkboxes were not filled, show an alert to fill and only after filling the action of the insert button

  • @Darlei Fernando Zillmer, the question is not duplicated, my problem is different. I will explain: When I do to enter into the database, if the process is completed, disables the button to enter that task, and what I want is that if it turns out that no checkbox is completed, does not finish the button process to the point of disabling it, to insert the task

Show 1 more comment

2 answers

1

Looking at your code I noticed some things:

<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required/>
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required/>

Those input has the same name="Notas" and they’re from type="checkbox".

  • If only one of those inputs can be selected at a time the best type for them would be the type="radio"
  • If both can be marked at the same time you keep the type="checkbox", but the ideal is you nay put the name="Notas" equal for both

Now look at these Keys in its object:

var dadosajax = {
    'tarefa' : $("#tarefa18").val(),

/// ; ↓ 
    'Notas' : $("#Notas11").val(), 
    'Notas' : $("#Notas12").val(),
/// ; ↑ Essa aqui esta sobrescrevendo a primeira

    'Observacao' : $("#Observacao18").val()
};

How the two entrances have the same key(Notes), the last will be kept, see the example below:

let obj = {
    'Notas': 11111,
    'Notas': 22222,
};
console.log( obj );


Correcting and making the check

First step I’ll change your input to the type='radio', for how they represent Sim and Não I believe you want the user to choose between one or the other. Another problem in these input is that the label of them is not with attribute for correct, this attribute must indicate the id of the target element. See below how it looked after the change:

<label for="Notas11"> Sim</label>
<input type="radio" name="Notas" id="Notas11" Value="Sim" required/>

<label for="Notas12"> Não</label>
<input type="radio" name="Notas" id="Notas12" Value="Não" required/>

Step two, we’ll do the check.
As you are already using jQuery and your input is now a input[type='radio'], that is, only 1 can this checked, your check can use the selector :checked and stay +/- like this:

let elementoChecked = $('input[name="Notas"]:checked');
/// ; Busca:               ↑     ↑              ↑
/// ; Elemento com a tag `input` |              |
/// ; Com o attributo `name` igual a `Notas`    |
/// ;                             Que esteja marcado (checked)

if( elementoChecked.length == 0 )
{
    /// ; Se entrar aqui nenhum elemento esta marcado (checked)
}

Step three, I’m removing that code if(confirm('Pretende registar esta atividade?')) this.disabled=true; of the onclick and put it within its function inserir_registo18 and in the onclick I’ll call the function inserir_registo18 passing as parameter this that at that moment is the button itself, the button will look like this

<button class="btn btn-info btn-sm botao" onclick="inserir_registo18(this);">Pequeno Almoço</button>

Fourth step, as you now already know which element this checked, just take the .val() of this element to place in its object dadosajax and as its function now takes as a parameter the button that was clicked you can disable it inside it, your code should be +/- like this:

function inserir_registo18( botao )
{
    let elementoChecked = $('input[name="Notas"]:checked');
    /// ; Busca:               ↑     ↑              ↑
    /// ; Elemento com a tag `input` |              |
    /// ; Com o attributo `name` igual a `Notas`    |
    /// ;                             Que esteja marcado (checked)

    if( elementoChecked.length == 0 )
    {
        /// ; Se entrar aqui nenhum elemento esta marcado (checked)
        alert('Você precisa escolher um valor');
        return false;
    }

    var dadosajax = {
        'tarefa' : $("#tarefa18").val(),
        'Notas' : elementoChecked.val(),
        'Observacao' : $("#Observacao18").val()
    };

    console.log('dadosajax:' , dadosajax);
 

    /// ; Desativar botão
    if(confirm('Pretende registar esta atividade?'))
        botao.disabled=true; 


    $.ajax({
        url: './insertarefa1',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        { 
        }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
    <div>
        <label for="Indicar">Comeu Bem: </label>
        <label for="Notas11"> Sim</label>
        <input type="radio" name="Notas" id="Notas11" Value="Sim" required />
        <label for="Notas12"> Não</label>
        <input type="radio" name="Notas" id="Notas12" Value="Não" required />
    </div>
    
    <input type="hidden" id="tarefa18" name="tarefa" value="30">
    <button class="btn btn-info btn-sm botao" onclick="inserir_registo18(this);">Pequeno Almoço</button>
    <button type="button" name="abrir18"><span class="glyphicon glyphicon-comment"></span></button>
    <div class="form-group" id="comentario18" style="display:none">
        <textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>
    </div>
</div>

References: label, jQuery :checked Selector

  • but there is a problem, I have several tasks that I have to put confirmation of yes and no, <input type="checkbox" name="Notas" id="Notas11" Value="Sim" required/>, If I use radio I can’t use the same name on each of them and I have to create several columns in the database and I want you to always record in the same column. For this reason I can not use radio and the checkbox in this way allows me to register always in the same column.

  • @Bruno, I think it’s only worth you edit the question and: Post more of these confirmations , If possible explain how you are generating this HTML with these confirmations. Ex: If they are generated by programming with a certain language (PHP,Javascript,...), put the code that this generating.

  • edited the question with the three-example code all on the same page.

1

Try it this way:

function inserir_registo18() {
  var dadosajax = {
    'tarefa': $("#tarefa18").val(),
    'Notas': $("#Notas11").val(),
    'Notas': $("#Notas12").val(),
    'Observacao': $("#Observacao18").val()
  };
  $.ajax({
    url: './insertarefa1',
    type: 'POST',
    cache: false,
    data: dadosajax,
    error: function() {

    },
    success: function(result) {}
  });
}
$(document).on('click', '.botao', function(e) {
  e.preventDefault();
  if (confirm('Pretende registar esta atividade?')) {
    if ($("#Notas11").is(':checked') || $("#Notas12").is(':checked')) {
      alert('Inserindo');
      inserir_registo18();
    } else {
      alert('Selecione um campo');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class="form-group">
  <div>
    <label for="Indicar">Comeu Bem: </label>
    <label for="Notas"> Sim</label>
    <input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
    <label for="check1"> Não</label>
    <input type="checkbox" name="Notas" id="Notas12" Value="Não" required />
  </div>
  <input type="hidden" id="tarefa18" name="tarefa" value="30">
  <button class="btn btn-info btn-sm botao">Pequeno Almoço</button><button type="button" name="abrir18"><span class="glyphicon glyphicon-comment"></span></button>
  <div class="form-group" id="comentario18" style="display:none">
    <textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>
  </div>
</div>
</div>

Browser other questions tagged

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