Deselect radio type input

Asked

Viewed 1,776 times

4

I have two inputs of the kind radio. Follow the code below:

 <input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" /> 
 <label for="isgift0">Teste 1</label>

 <input type="radio" id="isgift1" name="isgift" value="1" style="display: none;" /> 
 <label for="isgift1">Teste 2</label>

And I have the following code on jQuery:

$j('input[name=isgift]').click(function(){
    if($j('#isgift1').is(':checked')){
        $j(".gift-from").val(name_from);
        $j(".gift-to").val(name_to);
        $j(".mensagem-pedido").removeClass("divDisabled");
        $j(".box-gift").addClass("divActive");
        $j('#allow-gift-messages-for-order-container').show();
    }
    else if($j('#isgift0').is(':checked')){
        $j(".gift-from").val('Anônimo');
        $j(".gift-to").val(name_to);
        $j(".box-gift").removeClass("divActive");
        $j(".mensagem-pedido").addClass("divDisabled");
    }

How they are ìnputs of the kind radio And with the same names, you can only mark one of the two. But I needed to do something else that I’m not getting. I wish when the first ìnput,in the case with the id=isgift0, if it was marked and the user clicked on it, it was unchecked. I wanted to do this only for this input.

3 answers

2

Only the function to enable/disable the first "radio input"

$(function() {
    var check1 = 0;
    $('input[name=isgift]').click(function() {
        if($('#isgift1').is(':checked')){
           check1 = 0;
        }
        if ($('#isgift0').is(':checked')) {
            if(check1 != 0) { 
                $(this).prop('checked', false);
                check1 = 0;
            } else {
                check1 = 1;
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" /> 
<label for="isgift0">Teste 1</label>

<input type="radio" id="isgift1" name="isgift" value="1" /> 
<label for="isgift1">Teste 2</label>

Now "trying to run" with the code snippet reported in the question:

var $j = $;
var check1 = 0;
$j('input[name=isgift]').click(function(){
    if($j('#isgift1').is(':checked')){
        check1 = 0;
        $j(".gift-from").val(name_from);
        $j(".gift-to").val(name_to);
        $j(".mensagem-pedido").removeClass("divDisabled");
        $j(".box-gift").addClass("divActive");
        $j('#allow-gift-messages-for-order-container').show();
    }
    else if($j('#isgift0').is(':checked')){
        if(check1 != 0) { 
            $j(this).prop('checked', false);
            check1 = 0;
        } else {
            check1 = 1;
        }
        $j(".gift-from").val('Anônimo');
        $j(".gift-to").val(name_to);
        $j(".box-gift").removeClass("divActive");
        $j(".mensagem-pedido").addClass("divDisabled");
    }
});
 <input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" />
 <label for="isgift0">Teste 1</label>
 <input type="radio" id="isgift1" name="isgift" value="1" style="display: none;" />
 <label for="isgift1">Teste 2</label>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • His code is right, but what happens in this case is that he doesn’t even check the input and I wish that it could be checked and if the user clicked on it, it would be unchecked.

  • @Matheusportela I reviewed the question several times and realized that the need was different even. Edited, thanks for punctuating!

  • Samuel, I took a look and apparently the syntax is correct, but it hasn’t worked yet...

  • @Matheusportela Missing put the $j.

  • @DVD Put the $j, but it still didn’t work...

  • What didn’t work? The stackoverflow snippet is doing something different than it should?

  • @Samuelfontebasso The stackoverflow snippet is working correctly, but by putting this in my code, it doesn’t work. The input is marked, but it does not clear.

  • @Matheusportela I don’t know why use jQuery with $j, maybe it’s eliminating the conflict with another library. However, I edited the answer with a direct example about the code you left in the question. If there’s another stretch that’s in conflict with this one there’s no way I know..

  • @Samuelfontebasso I use jQuery with the $j, just as you said in your comment, to eliminate conflicts with other libraries. So, this example that you put up I had already done it, but it didn’t work either. And about the conflict, there’s nothing in my code that can do that, or that I use these inputs again.

  • Mark and uncheck one input with the code snippet you presented is ok. Go back, and start analyzing each step, use console.log at all to verify that each action is fired. Print text in the javascript console within the scope of the function fired with click to see if it is capturing the click on inputs then a console.log inside the test if the input is marked as checked or not and, if there is some error in javascript before this snippet everything is stopped and does not run, see this too. There’s no secret if something doesn’t work you have to find where it’s stopping..

  • @Samuelfontebasso I appreciate all your help and attention!

Show 6 more comments

2


With the function below, only the first radio is unchecked by clicking it again (run the test and see the messages in console log.. Every click on one radio executes a function block):

function exibirGift(){
              $('#allow_gift_messages').attr('checked','checked');
              $('#allow_gift_messages_for_order').attr('checked','checked');
              $('#gift-message-whole-message').attr('disabled',false);
              //$j('#allow_gift_messages_for_items').attr('checked','checked');
              $('#allow-gift-message-container').show();
              $('#allow-gift-messages-for-items-container').show();
            }
            function esconderGift(){
              $('#allow_gift_messages').attr('checked',false);
              $('#allow_gift_messages_for_order').attr('checked',false);
              $('#gift-message-whole-message').attr('disabled','disabled');
              //$j('#allow_gift_messages_for_items').attr('checked',false);
              $('#allow-gift-message-container').hide();
              $('#allow-gift-messages-for-items-container').hide();
            }
             var checado = false;
            $('input[name=isgift]').click(function(){
              var check1 = 0;
              var name_from = $(".nomeb").val();
              var name_to = $(".nomea").val();
              var isCartaoAdicionadoPagina = $('#cartao_adicionado_radio_productId').val();
              var isCartaoAdicionadoVerificacaoMensagem = $('#cartao_adicionado_product_id').val();
              if($(this).attr('id') != 'isgift0'){
                checado = false;
                //      $j(".gift-from").val(name_from);
                //      $j(".gift-to").val(name_to);
                //      $j(".mensagem-pedido").removeClass("divDisabled");
                //      $j(".box-gift").addClass("divActive");
                //      $j('#allow-gift-messages-for-order-container').show();
                console.log("2 marcado");
              }else{
                if(!checado){
                  this.checked = true

                  //        $j(".gift-from").val('Anônimo');
                  //        $j(".gift-to").val(name_to);
                  //        $j(".box-gift").removeClass("divActive");
                  //        $j(".mensagem-pedido").addClass("divDisabled");
                  console.log("1 marcado");
                }else{
                  this.checked = false;
                  console.log("1 desmarcado");
                }
                checado = this.checked;
              }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="isgift0" name="isgift" value="0" /> 
<label for="isgift0">Teste 1</label>

<input type="radio" id="isgift1" name="isgift" value="1" /> 
<label for="isgift1">Teste 2</label>

  • Unfortunately, it didn’t work...

  • @Matheusportela Take the test and see the messages that appear.

  • When I click to mark, it returns me "1 marked". When I click on input to uncheck it, also returns me "1 marked".

  • @Matheusportela Then there’s something else wrong with your code. Look at this image of how it works: https://i.stack.Imgur.com/Yrbkd.png

  • Here I put all the code used, along with the functions I also call and the way it is, it didn’t work. https://jsfiddle.net/vtLdgj34/

  • @Matheusportela updated the answer. The var checado = false;has to stay before the Istener $('input[name=isgift]').click(function(){

  • Yes, now it worked, thank you so much for all your help and attention!

  • @Matheusportela You’re welcome, my friend!

Show 3 more comments

1

I created a snippet and share here:

// itera com método do Array para compatibilidade
Array.prototype.forEach.call(document.querySelectorAll('[type=radio]'), function(radio) {
  radio.addEventListener('click', function() {
    var self = this;
    // obter elementos com o mesmo nome exceto o próprio e grava estado desmarcado
    Array.prototype.filter.call(document.getElementsByName(this.name), function(filterEl) {
      return self !== filterEl;
    }).forEach(function(otherEl) {
      delete otherEl.dataset.check
    })

    // grava estado baseado no estado anterior
    if (this.dataset.hasOwnProperty('check')) {
      this.checked = false
      delete this.dataset.check
    } else {
      this.dataset.check = ''
    }
  }, false)
})

// versão jQuery:
/*
$('[type=radio]').on('click', function(e) {
  $('[name=' + this.name + ']').not(this).data('check', false)
  if ($(this).data('check')) this.checked = false
  $(this).data('check', this.checked)
})
*/
<label><input type="radio" name="foo" value="1"/>foo = 1</label><br/>
<label><input type="radio" name="foo" value="2"/>foo = 2</label><br/>
<label><input type="radio" name="foo" value="3"/>foo = 3</label><br/>
<br/>
<label><input type="radio" name="bar" value="1"/>bar = 1</label><br/>
<label><input type="radio" name="bar" value="2"/>bar = 2</label><br/>
<label><input type="radio" name="bar" value="3"/>bar = 3</label><br/>

Browser other questions tagged

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