John Beasley
John Beasley

Reputation: 3089

Reusable function to return count of blanks

I have an onclick that is calling a function that checks for blanks.

The function successfully highlights the fields that are blank.

I need to return a count of the blanks in the form of a variable called 'error'.

The onclick is as follows:

$('#addUserSubmit').on('click', function(e) {
  e.preventDefault();

  let errors = "";

  let usr = new UserEdit();

  let uobj = {
    addfirstname: $('#addfirstname').val(),
    addlastname: $('#addlastname').val(),
    addemail: $('#addemail').val(),
    // few more 
  }
  
  checkblanks('#addfirstname', '#addfirstnameError');
  checkblanks('#addlastname', '#addlastnameError');
  checkblanks('#addemail', '#addemailError');

  if(errors > 0) {
    return false;
  } else {
    usr.addUser(uobj);
  }
});

Using the above, I want to be able to return the error count back from the function 'checkblanks'.

Here is function checkblanks():

function checkblanks(id, errorid) {
    let error = "";

    if($(id).val() == "") {
        $(errorid).show().text(' cannot be blank');
        $(id).css('border-color', 'red');
        error++;
        return error;
    } else {
        $(errorid).hide();
        $(id).css('border-color', '#ced4da');
    }
}

As you can see in the above example, I am trying to return error. I am just not sure how to access it within the onClick.

The above works to show the appropriate error message. I just need to get the count of the errors. How can I access the count of the errors within the onClick?

Upvotes: 0

Views: 64

Answers (3)

bel3atar
bel3atar

Reputation: 943

class UserEdit {
  addUser() {}
}

$('#addUserSubmit').on('click', function(e) {
  e.preventDefault();

  let usr = new UserEdit();
  const fields = ['addfirstname', 'addlastname', 'addemail']
  const uobj = fields.reduce(
    (acc, cur) => ({ ...acc,
      [cur]: $('#' + cur).val()
    }), {}
  )

  const errors = checkblanks(fields)
  console.log({ errors });
  if (errors > 0) {
    return false;
  } else {
    usr.addUser(uobj);
  }
});


function checkblanks(fields) {
  return fields.reduce((acc, cur) => {
    const id = '#' + cur
    const errorid = id + 'Error'
    if ($(id).val() === "") {
      $(errorid).show();
      $(id).css('border-color', 'red');
      return acc + 1
    } else {
      $(errorid).hide();
      $(id).css('border-color', '#ced4da');
      return acc;
    }
  }, 0)

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=addfirstname placeholder=firstname />
<div id=addfirstnameError style="display: none">Cannot be blank</div>
<input type=text id=addlastname placeholder=lastname />
<div id=addlastnameError style="display: none">Cannot be blank</div>
<input type=email id=addemail placeholder=email />
<div id=addemailError style="display: none">Cannot be blank</div>
<button id=addUserSubmit>Submit</button>

Upvotes: 0

Ben Stephens
Ben Stephens

Reputation: 3371

One approach could be something along the lines of:

Change checkblanks to:

function apply_error_state(id, errorid) {
    $(errorid).show().text(' cannot be blank');
    $(id).css('border-color', 'red');
}

function apply_non_error_state(id, errorid) {
    $(errorid).hide();
    $(id).css('border-color', '#ced4da');
}

function has_error(id) {
    return $(id).val() == "";
}

function check_for_errors_in_ids(ids) {
    let error_count = 0;
    
    ids.forEach(function(id) {
        if(has_error(id)) {
            error_count++;
            apply_error_state(id, id + 'Error');
        } else {
            apply_non_error_state(id, id + 'Error');
        }
    });
    
    return error_count;
}

And then in the event handler replace:

  checkblanks('#addfirstname', '#addfirstnameError');
  checkblanks('#addlastname', '#addlastnameError');
  checkblanks('#addemail', '#addemailError');

with:

  errors = check_for_errors_in_ids(['#addfirstname', '#addlastname', '#addemail']);

Upvotes: 1

Kinglish
Kinglish

Reputation: 23664

You're switching from text to numbers - plus trying to utilize errors in multiple functions.

In your first function change to let errors=0, then something like this:

errors += checkblanks('#addfirstname', '#addfirstnameError');
errors += checkblanks('#addlastname', '#addlastnameError');
errors += checkblanks('#addemail', '#addemailError');

Now, you just need to return a number from your checkblanks function

function checkblanks(id, errorid) {   
    if($(id).val() == "") {
        $(errorid).show().text(' cannot be blank');
        $(id).css('border-color', 'red');
        return 1;
    } else {
        $(errorid).hide();
        $(id).css('border-color', '#ced4da');
        return 0;
    }
}

Upvotes: 2

Related Questions