0

I'm trying to keep a checkbox checked whenever a given text input is not empty. At the moment, the text input box isn't responding to the event I added to it through jquery, and I'm wondering if there's something off in my code. (still quite new to jquery)

Here is my text input and checkbox:

<input type="text" id="textInput"/>

<input type="checkbox" id="checkBox" checked="checked" />

And here is my jquery code:

$('#textInput').on('click', function(){
    //if text input is not empty 
    if($('#textInput').val() !== ''){
        //if checkbox not checked, check it
        if($('checkBox').checked !== 'checked'){
            $('checkBox').checked = 'checked';
        }
    }
})
1
  • hey. man! you should pay attention to selectors and learn how to debug you code. I'll provide possible solution below Commented Jul 12, 2021 at 14:21

2 Answers 2

1

You can affect the checkbox checked state via .prop() - and in this case we can just set it to the truthy $('#textInput').val() !== ''.

$('#textInput').on('blur', function() {
  $('#checkBox').prop('checked', $('#textInput').val().trim() !== '');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="textInput" />
<input type="checkbox" id="checkBox" checked="checked" />

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

Comments

0

You should call function to check on page load(ready), and every text field change. I didn't test my solution, but it should be fine

const textInput = $('#textInput');
const checkbox = $('#checkBox');

function setCheckboxState() {
  const text = textInput.val();
  if (text) {
    checkbox.prop('checked', true);
  }
}

setCheckboxState();
textInput.on('focus change keyup', setCheckboxState);

Comments

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.