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 {
})
use keyup() function to check the val and conditions to check an uncheck the checkbox tyr this
$(".boxtext").keyup(function(){
if($(this).val()!= ""){
$('.boxcheck').prop('checked',true);
}else{
$('.boxcheck').prop('checked',false);
}
})
updated
and for your last problem.. i think it will be better if you disable your checkbox.. so that user won't be able to uncheck...
$('.boxcheck').prop('disabled',true);
updated fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With