How to check if a checkbox is javascript checked

Asked

Viewed 28,774 times

0

I have a problem I need to check if a checkbox is selected. I happen to have a form with values that are loaded by ajax requests to the server. after having the data loaded is that he should check the checkbox as I do this, I have to see if the select was empty before.

if (document.getElementById('trabalho').checked) {   

} 
       <div  class="col-xs-12 col-md-3">
                    <input type="checkbox" name="trabalho" value="trabalho" checked="true" id="trabalho">Trabalho </input>
                    <input type="checkbox" name="residencia" value="residencia" id="residencia">Residência</input>
                    <select  class="form-control" placeholder="Residencia" id="opcao" sytle="display: none!important;">
                        <option value="todos"  selected="selected"> Todos</option>
                        <option value="1antes">1 ano antes</option>

                    </select>
                </div>
  • Hello, Unfortunately I didn’t understand your question. Can try to put an example?

  • Your condition already returns true if the checkbox is selected. da to put a better example?

  • yes already this selected I have two and switch between the two, is to generate a chart..

2 answers

1

You can use this function to check one or more checkboxes on your screen if they are selected or not. I don’t know if it’s the best solution, but I hope I helped.

function verificarCheckBox() {
    var check = document.getElementsByName("itemCheck"); 

    for (var i=0;i<check.length;i++){ 
        if (check[i].checked == true){ 
            // CheckBox Marcado... Faça alguma coisa...

        }  else {
           // CheckBox Não Marcado... Faça alguma outra coisa...
        }
    }
}
  • would if you had onclick but by default this checked.

0

Hello, I don’t know if I understand your question very well, but I understand that you would like there to be a check if the checkboxes are selected at the time the AJAX request arrives, that’s it?


In that case, I created a Jsfiddle for you to check the behavior.

  • I have no button. my dear he will show the whole chart only after and I do filtering

  • No matter where you will shoot the event, but you will have to fire the ajax request at some point. What, for us, you haven’t clarified is where do you want to shoot this.

  • I want to shoot after check if you have work selected, what I can do is not have anything selected by default, but I want to show the chart already filled

  • If you already start "WORK" as selected, nothing prevents you from placing this event when the page or form is loaded. If you are already selected, then we can assume that we want to start the event. Another option you can have is to place the event in the checkbox click.

  • yes but now the question is not that I’m not getting the value

Browser other questions tagged

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