Activating event from checkbox

Asked

Viewed 67 times

1

I tried to do the checkbox to change a input of hidden for text, but I don’t know what I’m missing.

function myFunction() {

    const selecionado = document.querySelector("#quant");
    var checkBox = document.getElementById("ch_quant");

    var input = document.getElementById("quant").type = 'hidden';


    if (checkBox.checked == true){
       document.getElementById("quant").type = 'text'
    }
    else {
        document.getElementById("quant").type = 'hidden'
    }
}
<div class="form-group col-md-12">
  <label for="nome">Marque P/ Informar Estoque</label>
  <input type="checkbox" id="ch_quant" name="ch_quant" required>
  <input type="hidden" id="quant" name="quant">
</div>

  • 2

    Where you call that function myFunction?

  • said everything not this nowhere, would have how to show me how it would be correct because I am student so I am very new.

  • Your question has an answer on this topic: https://answall.com/questions/5563/comorverifica-com-jquery-se-existe-um-checkbox-checado using jQuery.

1 answer

3


First of all you should call the function you created when there is change in the checkbox with the onchange="myFunction(this)".

Second, with the this you pass the function parameter itself input (<input type="checkbox" id="ch_quant" name="ch_quant" onchange="myFunction(this)" required>).

After that just check if it’s marked or not, just like you’ve already done.

function myFunction(checkbox) {

  if (checkbox.checked)
    document.getElementById("quant").type = 'text'    
  else 
    document.getElementById("quant").type = 'hidden'
    
}
<div class="form-group col-md-12">
  <label for="nome">Marque P/ Informar Estoque</label>
  <input type="checkbox" id="ch_quant" name="ch_quant" onchange="myFunction(this)" required>
  <input type="hidden" id="quant" name="quant">
</div>

  • 1

    I think you meant "with the this you pass the function parameter itself checkbox" (not "the input itself"). Another detail is that you can simply do if (checkbox.checked) - compare a boolean value with == true is redundant

  • The checkbox is not the input? I think so, see: <input type="checkbox"...

  • @Natan Hidden/text is also input, so I think it would be clearer to say which input is being passed :) That’s what I meant. Sorry if my comment got confused

  • @hkotsubo exactly, is the input type="checkbox" which is past, could be clearer kk. Although it is explicit that passes the próprio input

Browser other questions tagged

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