I would like to create a function in jquery where, if a input text box has content, check the checkbox. if it is blank, uncheck the checkbox.
<form>
<input class="boxcheck" type="checkbox">
checkbox
<input class="boxtext" type="text">
text here
</form>
The checkbox and the text input will in the beginning be empty but if a user decides to write something into the text box, the checkbox should be automatically checked if it isn’t checked already by the user.
One other issue might be that a user will type something and this function will check the checkbox, but if a user goes back to the input box and deletes the contents in the input box, the checkbox should be unchecked automatically also.
Last problem I can think of would be if the user writes something into the text box, and this function checks the checkbox but the user for some odd reason unchecks the box, would it be possible to force check the checkbox again?
I have been playing around with the keyup and prop triggers but I am having absolutely no luck. I am also very new to JavaScript.
The code I’ve been playing around is something like:
$('input[text]').keyup(function(){
if (this.value.length > 0) {
$('input[name="checkbox"]').prop('disabled', false)
} else {
})
I’d suggest handling the blur event in addition to keyup, because that covers any cases where the user changes the textbox value without the keyboard (copy/cut/paste/drags’n’drops/etc.), without needing to worry about which browsers do or don’t let you handle clipboard events:
Demo: http://jsfiddle.net/WTVEn/
Note that although I’ve included code that stops the user changing the checkbox, if it can’t be manually edited why do you need the checkbox at all?