Javascript function to mark checkbox depending on condition

Asked

Viewed 43 times

-1

I need to do an if Else function in Javascript that if the column "value_set" is equal to '0,00', then the checkbox is checked, if not, the checkbox remains unchecked. This function needs to be executed when loading the page automatically.

What I’ve already tried?

$(document).ready(function () {

        var valor_conjunto = '0,00';
    
    if (valor_conjunto == '0,00') {
      $('#checkbox').each(function() {
        this.checked = true;               
      });
      
    } else {
        $('#checkbox').each(function() {
        this.checked = false;               
      });
    }
    
}

I’ve tried several codes, but the closest was this, I’m a beginner with Javascript, so I’m not sure I’m missing any part of the code. Fiddle link with question code: http://jsfiddle.net/fqnwphx5/3/

1 answer

2

In your example you are using jQuery with an ID selector ($('#checkbox')), then you don’t need to use a each, because it will return an element only.

Also, use prop('checked', true); to set checked in an input:

$(document).ready(function () {
    var valor_conjunto = '0,00';
    
    if (valor_conjunto == '0,00') {
      $('#checkbox').prop('checked', true);               
    } else {
        $('#checkbox').prop('checked', false);           
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox"> Checkbox 1

Browser other questions tagged

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