Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form submit if checkbox is unchecked

I'm using some Ajax / Javascript to prevent the form submit if an input field is empty.

$(function() {

    var form = $('#contact-form-edc');

    $(form).submit(function(e) {
        e.preventDefault();


        var formData = $(form).serialize();

  if (document.getElementById("nachricht-field").value.length < 10) {
    document.getElementById('error-nachricht').style.display = "";
  } else {

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })

        .done(function(response) {
         document.getElementById('success').style.display = "";
          document.getElementById('error').style.display = "none";
      document.getElementById('error-nachricht').style.display = "none";

            $('input').val('');
   $('textarea').val('');
   $('.button').val('Abschicken');
   $('input[name=datenschutz]').attr('checked', false);
        })
        .fail(function(data) {
           document.getElementById('error').style.display = "";
            document.getElementById('success').style.display ="none";
        });

  }

    });

});

The script works fine but do not note the checkbox of the form. The checkbox

<input type="checkbox" name="datenschutz" value="Datenschutz" required="required" >

is required as well but the user can submit the form without checking the checkbox. Is there a small script which I can implement in the current Ajax-Script?

like image 511
susanloek Avatar asked Jan 08 '23 01:01

susanloek


2 Answers

Use this way:

$(form).submit(function(e) {
    e.preventDefault();
    if ($(this).find('input[name="datenschutz"]')[0].checked === false)
      return false;
    // rest of form

If you want to add a message, you can go ahead this way:

$(form).submit(function(e) {
    e.preventDefault();
    if ($(this).find('input[name="datenschutz"]')[0].checked === false) {
      alert("Please accept the terms and conditions!");
      return false;
    }
    // rest of form
like image 170
Praveen Kumar Purushothaman Avatar answered Jan 09 '23 18:01

Praveen Kumar Purushothaman


I'd suggest enabling the submit button when the check-box is checked:

// binding an anonymous function to handle the change event:
$('input[name=datenschutz]').on('change', function () {
    var input = this;

    // navigating to the form 'this.form',
    // finding the submit button (obviously correct the
    // selector),
    // setting the disabled property of the submit button to
    // to be false when the check-box is checked, and true
    // when the check-box is unchecked:
    $(input.form).find('submitButtonSelector').prop('disabled', !input.checked});
});
like image 22
David Thomas Avatar answered Jan 09 '23 18:01

David Thomas