Mohammad
Mohammad

Reputation: 127

Check form to see if any inputs has value with jQuery each method

I want to return false form and run css/focus event on selectors.

How to avoid form submission when using jQuery.each function?

This code doesn't work now but if you replace 'return true;' to ' return false;' works fine but doesn't submission form!

Please help me, thanks

HTML CODE:

<form id="formdata" method="post" action="">
    <div class="title">Ajax To Send Data And Save In PHP</div>

    <span>Fullname:</span>
    <input type="text" id="fullname" name="fullname" >

    <span>Email:</span>
    <input type="text" id="email" name="email" >

    <span>Comment:</span>
    <textarea name="comment" id="comment" cols="30" rows="5" ></textarea>

    <button type="submit">Create Data</button>
    <br>
    <div id="result"></div>
</form>

JS CODE:

$(document).ready(function () {

    var all_elements = '#formdata input[type=text]';

    $(all_elements).blur(function(){
        $(this).each(function(n, element){
           $("#" + element.id).prev().css("color", "#555");
           $("#" + element.id).css("border", "1px solid #CCC");
        });
    });

    $("#formdata").on('submit',(function() {

        $(all_elements).each(function(n, element){
            if ($(element).val()=='') {
                alert('Field '+element.id+' must have a value');
                $("#" + element.id).prev().css("color", "#F00");
                $("#" + element.id).css("border", "1px solid #F00");
                $("#" + element.id).focus();

                return false;
            }
        });
        return true;

        alert('Form submited, done!');

        }
    ));
});

Upvotes: 1

Views: 934

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle

The problem is that the return false; you have now will just prevent the foreach statement from continuing (and not the form), so you could add an extra variable called submit for example has true by default as value and if $(element).val()=='' achieved change it to false, then make a condition after each statement that will submit or prevent the submit based on this variable :

var submit = true;

$(all_elements).each(function(n, element){
  if ($(element).val()=='') {
      alert('Field '+element.id+' must have a value');
      $("#" + element.id).prev().css("color", "#F00");
      $("#" + element.id).css("border", "1px solid #F00");
      $("#" + element.id).focus();

      submit=false;

      return false;
  }
});

if(submit){
  alert('Form submited, done!');

  return true;
}
else
  return false;

Hope this helps.


Working Snippet

$(document).ready(function () {

  var all_elements = '#formdata input[type=text]';

  $(all_elements).blur(function(){
    $(this).each(function(n, element){
      $("#" + element.id).prev().css("color", "#555");
      $("#" + element.id).css("border", "1px solid #CCC");
    });
  });

  $("#formdata").on('submit',function() {
    var submit = true;

    $(all_elements).each(function(n, element){
      if ($(element).val()=='') {
        alert('Field '+element.id+' must have a value');
        $("#" + element.id).prev().css("color", "#F00");
        $("#" + element.id).css("border", "1px solid #F00");
        $("#" + element.id).focus();

        submit=false;

        return false;
      }
    });

    if(submit){
        alert('Form submited, done!');

        return true;
    }else
      return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formdata" method="post" action="">
  <div class="title">Ajax To Send Data And Save In PHP</div>

  <span>Fullname:</span>
  <input type="text" id="fullname" name="fullname" >

  <span>Email:</span>
  <input type="text" id="email" name="email" >

  <span>Comment:</span>
  <textarea name="comment" id="comment" cols="30" rows="5" ></textarea>

  <button type="submit">Create Data</button>
  <br>
  <div id="result"></div>
</form>

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You'd do that like this

$(document).ready(function () {
    var all_elements = $('#formdata input[type=text]').on('blur', function(){
        $(this).prev().css({
            color  : "#555",
            border : "1px solid #CCC"
        });
    });

    $("#formdata").on('submit', function() {
        var valid = all_elements.filter(function() {
            var ret = this.value.trim() === "";
            if (ret) {
                alert('Field ' + this.id + ' must have a value');
                $(this).prev().css({
                    color  : "#F00",
                    border : "1px solid #F00"
                }).focus();
            }
            return ret;
        }).length === 0;

        if ( valid ) alert('Form submited, done!');
        return valid;
    });
});

Upvotes: 1

DinoMyte
DinoMyte

Reputation: 8858

Try this :

$(document).ready(function () {

    var all_elements = '#formdata input[type=text]';

    $(all_elements).blur(function(){
      $(this).each(function(n, element){
        $("#" + element.id).prev().css("color", "#555");
        $("#" + element.id).css("border", "1px solid #CCC");
      });
    });

    $("#formdata").on('submit',function(e) {

        var validationFailed = false;
        $(all_elements).each(function(n, element){
            if ($(this).val() === '') {
              alert('Field '+element.id+' must have a value');
              $("#" + element.id).prev().css("color", "#F00");
              $("#" + element.id).css("border", "1px solid #F00");
              $("#" + element.id).focus(); 
              validationFailed = true;
            }
        });

         if(validationFailed)
          e.preventDefault();
        else
          alert('Form submited, done!');

        });

    });

Example : https://jsfiddle.net/DinoMyte/43xk9ta2/

Upvotes: 1

Related Questions