Displaying alerts for blank fields I'm trying to make my code easier to understand by making it more correct and maintainable.

Here's the code I'm trying to simplify:

       $(document).ready(function(){
  $('.opretbruger').on('click', function(){
    if (opretbruger() === true){

    }
  });
});

var opretbruger = function(){
  if($('#brugernavn').val() === ''){
     alert('remember Email');
      return false;
  }

  if($('#pass1').val() === ''){
    alert('remember password');
    return false;
  }

  if($('#pass2').val() === ''){
    alert('remember password');
    return false;
  }

  if($('#fornavn').val() === ''){
    alert('remember your name');
    return false;
  }

  if($('#efternavn').val() === ''){
    alert('remember your last name');
    return false;
  }

  return true;
};


Here's my attempt at simplifying it:

       $(function () {
     var $login = $("#login"),
         $pwd = $("#pass"),
         $usr = $("#brugernavn");

     $login.on("submit", function (event) {
         var msg = "Husk ",
             usr = ($usr.val().trim() !== ""),
             pwd = ($pwd.val().trim() !== "");

         msg += !usr ? " brugernavn" : "";
         msg += !usr &amp;&amp; !pwd ? " og " : "";
         msg += !pwd ? " kodeord" : "";

         (pwd &amp;&amp; usr) || alert(msg);

         return (pwd &amp;&amp; usr);
     });
 });
Let me make sure I understand the problem.  You have a number of fields on the page where a value is required; when the user submits the page, and any of the fields are blank, you'd like the page to display a Javascript alert instead of submitting the form.  Yes?

I'd suggest you use an unobtrusive technique as follows:


If a field is required, it is marked with a "required" css class.  This can be a dummy class if you like.
Each field that is required is associated with a data attribute which specifies its human-readable name in the appropriate language
The submit button inspects all fields that are marked with the style and displays the names.


So to mark up a required field, use this pattern:

&lt;input ID="login" class="required" data-name="login"/&gt;


Then include this bit of code in your common script.  There's nothing page- or field- specific in it, so you can include it in every page if you want (e.g. in "common.js" or whatever):

$(document).ready(function(){
    var validate = function(e){
        var emptyFields = [];
        $(".required").each(function(){
            if ($(this).val().trim() == "") emptyFields.push($(this).data("name")); 
        }
        if (emptyFields.length != 0) {
            e.preventDefault();
            var message = "You forgot these fields: " + emptyFields.join(","); 
            alert(message);
        }
    }

    $(":submit").click(validate);
})


This ought to cover any additional fields or really any additional pages that require this sort of validation.