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

1

2 Answers 2

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">

Sign up to request clarification or add additional context in comments.

3 Comments

@Fayakon, logically the solution should work. It is really hard to tell the issue without seeing the example code with json:)
just curious how we pass any variable as value? $('input[type=checkbox][variable=1]').attr('checked', true);
@Fayakon, if v is the value then you can write $('input[type=checkbox][value='+v+']').attr('checked', true);
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">

3 Comments

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 you never told before that it is loading from json. In that case you need to show more code which loads json
Thanks figured it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.