By clicking the checkbox disable the button

Asked

Viewed 618 times

1

I have the following code that automatically brings the freight value:

foreach($dados->cServico as $linhas) {

    if($linhas->Codigo == '04014'){
        $servico = "SEDEX";
    }
    if($linhas->Codigo == '04510'){
        $servico = "PAC";
    }
    echo "<input type='radio' name='Servico[]' value='".$linhas->Valor."' id='servicos' onclick='desabilitar()'> <strong>".$servico."</strong><br>";

}

With that code, I have the following result:

inserir a descrição da imagem aqui

While the user does not select which mode he will want, the button is disabled. For this I am using the following code:

    function desabilitar(){
        if(document.getElementById('servicos').checked == true){
             document.getElementById('botao').disabled = "";
        }
        if(document.getElementById('servicos').checked == false){
             document.getElementById('botao').disabled = "disabled";
        }
    }
<button type="submit" class="btn btn-primary col-lg-12 col-xs-12" style="margin-top: 10px" id="botao" disabled><h4>Finalizar <i class="fa fa-angle-double-right" aria-hidden="true"></i></h4></button>

The problem is when I select Sedex, the button works perfectly, but when I click on the PAC, the button again disables. How do I click the Sedex or PAC button is enabled, otherwise the button is disabled?

1 answer

1


You cannot have duplicate Ids, HTML syntax only allows 1 unique ID per page.

Mute id='servicos' class-oriented class='servicos' or passes the this in HTML like this: onclick='desabilitar(this)'> and then:

function desabilitar(el) {
  document.getElementById('botao').disabled = !el.checked;
}
  • 1

    Thanks Sergio. It worked.

  • Sergio. I’m sorry, I implemented your code, but how would I get the input value, because I needed to get the freight value. In the case of the ID I took it this way: valueFrete = Document.getElementById("services"). innerHTML;

  • @Fox.11 inside the function or outside? Where do you call the code that looks for this value? So without testing I think you can use document.querySelector("[name='Servico[]']:checked");

  • Hello Sergio. It would be within the function.

  • 1

    @Fox.11 in this case el.valuegives the value of the input whose this you passed in onclick='desabilitar(this)'>

  • 1

    Perfect Sergio. Thanks again.

Show 1 more comment

Browser other questions tagged

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