1

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.

I tried 2 things:

 $(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
        if ($(this).val() == 
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
            ($(this).prop('checked', true));
    });

And

$(document).ready(function() {
    var checkBox = 
[
     ["OPTIN_NEWSLETTER_STARTER_INDEPENDANT", 
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];

for (var i = 0; i < checkBox.length; i++) {
        if (checkBox[i][1] == "Yes") {
            if ($('input[name="' + checkBox[i][0] + '"]')) 
            {
                $('input[name="' + checkBox[i][0] + 
'"]').prop("checked", true).change();
            }
        }
    };

This is my html checkbox:

<label class="yesNoCheckboxLabel">
                                        <input type="checkbox" 
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136" 
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" 
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%" 
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>

It would be great to have someone's insights, thanks!

Kind regards, Loren

2
  • $(this).prop('checked', true) should work. Could you provide a Minimal, Complete, and Verifiable example ? stackoverflow.com/help/mcve Commented Apr 12, 2018 at 12:18
  • I tested your code and it is working as you described how you want it to work; except that the first document.ready() block that you pasted, had incomplete closing brace and parenthesis, so I had to correct it. Are you sure that was not the cause and thus you had an error on the page? Commented Apr 12, 2018 at 12:27

1 Answer 1

1

I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below

For jquery 1.5 or below

 ($(this).prop('checked', true));

 $(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {

        if ($(this).val() == 
"vehicle1")
            ($(this).prop('checked', true));
    });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
  <input type="checkbox" name="vehicle1" value="vehicle1"> I have a car 
</form>

and last thing make sure that value must be same for this condition

$(this).val() == "vehicle1"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'm afraid I just misplaced my <script> tags, it's working indeed :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.