I have an input and a checkbox. I have managed to change the value in the input on clicking the checkbox, and un clicking etc which works fine.
I'm looking to auto set the checkbox to be checked on page load only if the input value = yes, as this input value is being loaded dynamically via php and may not be yes.
HTML
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
JQUERY
$('#yourCheckboxId').click(function() {
if ($('#yourCheckboxId').is(':checked')){
$('#inputId').val('yes');
}
if (!$('#yourCheckboxId').is(':checked')){
$('#inputId').val('no');
}
});
You'll notice that even though the value in the input is set to yes, on page load, the checkbox isn't checked. This is what I have so far, see jsfiddle here: /
Thanks
I have an input and a checkbox. I have managed to change the value in the input on clicking the checkbox, and un clicking etc which works fine.
I'm looking to auto set the checkbox to be checked on page load only if the input value = yes, as this input value is being loaded dynamically via php and may not be yes.
HTML
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
JQUERY
$('#yourCheckboxId').click(function() {
if ($('#yourCheckboxId').is(':checked')){
$('#inputId').val('yes');
}
if (!$('#yourCheckboxId').is(':checked')){
$('#inputId').val('no');
}
});
You'll notice that even though the value in the input is set to yes, on page load, the checkbox isn't checked. This is what I have so far, see jsfiddle here: http://jsfiddle/0z9agrw8/1/
Thanks
Share Improve this question edited Nov 30, 2017 at 21:20 Joel Rosen asked Nov 30, 2017 at 21:14 Joel RosenJoel Rosen 1571 silver badge11 bronze badges 2- Possible duplicate. Definitely along the same logic lines: stackoverflow./questions/47576449/… – Taplar Commented Nov 30, 2017 at 21:17
- In PHP, you just need to add the "checked" prop to your checkbox input if the input value is yes. – Justin Heath Commented Nov 30, 2017 at 21:24
3 Answers
Reset to default 5
var input = $('#inputId').val()
if(input === "yes"){
$("#yourCheckboxId").prop('checked', true);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
Do this on page load:
if($('#inputId').val() == 'yes') {
$('#yourCheckboxId').prop('checked', true);
}
If you always want it to be checked on page load, you can simply add the "checked" attribute
eg
<input type="checkbox" id = "yourCheckboxId" checked>
If it's more plicated than that, the other answers will work nicely