3

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.net/0z9agrw8/1/

Thanks

2
  • Possible duplicate. Definitely along the same logic lines: stackoverflow.com/questions/47576449/… 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. Commented Nov 30, 2017 at 21:24

3 Answers 3

5

var input = $('#inputId').val()

if(input === "yes"){
  $("#yourCheckboxId").prop('checked', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">

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

Comments

1

Do this on page load:

if($('#inputId').val() == 'yes') { 
    $('#yourCheckboxId').prop('checked', true);
}

Comments

0

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 complicated than that, the other answers will work nicely

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.