help correct the error with validation. The challenge is this:

There is a check boxes and input field. if any of the check boxes is marked, and nothing is entered in the input field, a validation prohibiting the sending of the form should work and div.demo will be red framed. it works, but if I mark and enter text, then when sending it is still marked with a frame. in javascript is not strong. I can not figure out what I'm doing wrong.

 $('.checker').change(function() { if (this.checked) { $('#altField').prop('required', true); if ($("#altField").val().length === 0) { $("button").click(function() { $(".demo").addClass("redb"); }); } } else { $('#altField').prop('required', false); $("button").click(function() { $(".demo").removeClass("redb"); }); } }); 

https://jsfiddle.net/d82knaz4/

  • And could you add steps to play. I tried several options, everything worked fine. - Vartlok
  • mark any check box, enter something in the input field and click the send button. :) it sends as it should, but at the moment it loads still the red frame pops up :( - akasergej

1 answer 1

You need to change the handler a bit to make it like this:

 $('.checker').change(function () { if(this.checked) { $('#altField').prop('required', true); $("button").click(function(){ if( $("#altField").val().length === 0 ) { $(".demo").addClass("redb"); } else { $(".demo").removeClass("redb"); } }); } else { $('#altField').prop('required', false); $("button").click(function(){ $(".demo").removeClass("redb"); }); } }); 

Unlike your variant, there is a condition for class deletion when the field is not empty. Also here, an event per click is always assigned, and not just when the field is empty. Those. this fixes the problem when something is entered into the field, then tick and remove everything from the field. The field will be required, but there will be no red box.

  • Thank you very much, everything is fine now works :) - akasergej