0

I want to set checkbox checked on document load, if check box value="1", and unchecked if value="0".

<input type="checkbox" value="1">
<input type="checkbox" value="0">
<input type="checkbox" value="1">

Jquery: which is wrong, tried many things

$(document).ready ('input[type="checkbox"]', function(event) {
  if ($(this).val==1) {
    $(this).is(":checked")
  }
});

JSFiddle

Pedram
  • 15,766
  • 10
  • 44
  • 73
Fayakon
  • 1,173
  • 4
  • 23
  • 48
  • Possible duplicate of [Get checkbox with specific value](https://stackoverflow.com/questions/10930048/get-checkbox-with-specific-value) – Pedram Nov 02 '19 at 13:30

2 Answers2

4

.ready() accepts a function as the single parameter which is executed after the DOM is ready.

You do not need any condition to check the value manually. You can simply use attribute selector:

$('input[type=checkbox][value=1]').attr('checked', true);

$(document).ready(function() {
  $('input[type=checkbox][value=1]').attr('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1">
<input type="checkbox" value="0">
<input type="checkbox" value="1">
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • @Fayakon, logically the solution should work. It is really hard to tell the issue without seeing the example code with json:) – Mamun Nov 02 '19 at 13:33
  • just curious how we pass any variable as value? $('input[type=checkbox][variable=1]').attr('checked', true); – Fayakon Nov 02 '19 at 13:50
  • 1
    @Fayakon, if `v` is the value then you can write `$('input[type=checkbox][value='+v+']').attr('checked', true);` – Mamun Nov 02 '19 at 13:56
1

There are two errors. First this line ready ('input[type="checkbox"]', function(event) { .ready receives a callback function and your code is wrong there. Secondly in if ($(this).val==1) { val is a method. So that will require braces. You can nly use attribute selector and marked it as checked.Also $(this).is(":checked") return a boolean value but it never checks a checkbox

$(document).ready(function() {

  $('input[type="checkbox"][value="1"]').prop('checked', true)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1">
<input type="checkbox" value="0">
<input type="checkbox" value="1">
brk
  • 48,835
  • 10
  • 56
  • 78
  • data is loading in json format, your code works fine with hardcore value, but when json is changing value to 0/1 checkbox is not changing. – Fayakon Nov 02 '19 at 13:29
  • @Fayakon you never told before that it is loading from json. In that case you need to show more code which loads json – brk Nov 02 '19 at 13:30
  • Thanks figured it out. – Fayakon Nov 02 '19 at 13:34