I am experiencing trouble as I want to make checkbox value checked when site loads and the visitor can uncheck it. id field is dynamic inside input so I need to check based on name and value I suppose.
I used jQuery to make it checked, but nothing happens
jQuery(document).ready(function($) {
$("input.myclass[name='test-case'][value='yes']").prop("checked", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="test-case[]" id="cbopt-AAljenwo" value="yes">
Not sure if this is correct value of marking input as checked. User also can uncheck box if he doesn't like the option. Any help appreciated.
3 Answers 3
The best way to achieve this would be to put a checked attribute in the HTML. However you state that the HTML is being generated for you, so you don't have that option.
The second best option would be to target the checkbox by its id, however that has the same issue for you as the id is dynamically generated at runtime.
Your last resort is to then select the element by its name and value, which is what your jQuery is trying to do, however there's a couple of issues. Firstly the checkbox you're targeting has no class and the name attribute has a [] suffix which you need to include. Try this:
jQuery($ => {
$('input[name="test-case[]"][value="yes"]').prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="test-case[]" value="yes">
Comments
You can simply add checked attribute to the input element to make it checked when the page is loaded:
<input type="checkbox" checked="checked"/>
Thanks
1 Comment
simply that:
const theChexbox = document.querySelector("input[name='test-case[]']")
theChexbox.checked = true
<input type="checkbox" name="test-case[]" id="cbopt-AAljenwo" value="yes">
checked="checked"in HTMLcheckedattribute to the checkboxid field is dynamic inside input so I need to check based on name and value