I want to make a text field that triggers when a person writes his birth day down. For example 00.00.0000 or 00/00/0000. It is currently working, but not consistent. If I delete the birth day, after written it correctly in the text box then the submit button I activated through the script stays activated. How can I make the script recursive, so the button falls back to disabled when the text field isnt correctly filled anymore? “While” does not seem to work here.
<script> $('.cart_note').on('input', function(){ if($(this).val().length == 10){ var pattern =/^([0-9]{2}).([0-9]{2}).([0-9]{4})$/; if(pattern.test($(this).val())){ $('.btn-submit').removeAttr('disabled'); $('.enter_dob').text('Vielen Dank!'); }else{ $('.cart__submit').attr('disabled','disabled'); $('.enter_dob').text('Bitte das Geburtsdatum im Format TT.MM.JJJJ eingeben.'); } }else{ $('.cart__submit').attr('disabled','disabled'); $('.enter_dob').text('Bitte das Geburtsdatum im Format TT.MM.JJJJ eingeben.'); } }) </script>
Answer
You remove the disabled
attribute when all is good, but don’t “put it back” when regex doesn’t match
<script> $('.cart_note').on('input', function(){ if($(this).val().length == 10){ var pattern =/^([0-9]{2}).([0-9]{2}).([0-9]{4})$/; if(pattern.test($(this).val())){ $('.btn-submit').removeAttr('disabled'); $('.enter_dob').text('Vielen Dank!'); }else{ $('.btn-submit').addAttr('disabled'); //ADD HERE $('.cart__submit').attr('disabled','disabled'); $('.enter_dob').text('Bitte das Geburtsdatum im Format TT.MM.JJJJ eingeben.'); } }else{ $('.btn-submit').addAttr('disabled'); //ADD HERE $('.cart__submit').attr('disabled','disabled'); $('.enter_dob').text('Bitte das Geburtsdatum im Format TT.MM.JJJJ eingeben.'); } }) </script>
Cleaner code
You could also clean up your code so there are no two identical else
branches:
$('.cart_note').on('input', function(){ var pattern =/^([0-9]{2}).([0-9]{2}).([0-9]{4})$/; if($(this).val().length == 10 && pattern.test($(this).val())){ $('.btn-submit').removeAttr('disabled'); $('.enter_dob').text('Vielen Dank!'); }else{ $('.btn-submit').addAttr('disabled'); //ADD HERE $('.cart__submit').attr('disabled','disabled'); $('.enter_dob').text('Bitte das Geburtsdatum im Format TT.MM.JJJJ eingeben.'); } })