0

I need to be able to set a counter to monitor how many errors have been generated when a form is submitted. Errors are highlighted by a css class .validmissing.

So if user has 5 errors on submit - counter is set to 1

If user resubmits the form and then gets 3 errors my counter needs increment to 2 in the same session.

<script type="text/javascript">
  var ErrorCounter = 0;
    $(document).ready(function() {
    if($('.validmissing').length > 0) {
       ErrorCounter = 1;
    else{
    ErrorCounter = 0;
          }
    });
  </script> 

Do i need to set a cookie or a session variable?

2 Answers2

0

you can use cookie or session variable that will work but better is use the input hidden filed where you have previous counter stored.

HTML

<form method="get">
<input type="hidden" value="" name="counter" id="counter" />
..........
..........
</form>

Javascript

 <script type="text/javascript">

//http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript


 function getParameterByName(name)
    {
      name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
      var regexS = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(window.location.search);
      if(results == null)
        return 0;
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }




      var ErrorCounter = 0;
        $(document).ready(function() {
        $("#counter").val(getParameterByName("counter"));
        if($('.validmissing').length > 0) {
           ErrorCounter = $("#counter").val();
           ErrorCounter = 1*ErrorCounter + 1;
           $("#counter").val(ErrorCounter);
        });
</script> 
gaurang171
  • 9,032
  • 4
  • 28
  • 30
  • Thanks i'll try that, i'm trying to avoid setting a cookie - but cant use php so will a simple html hidden field work? – user1010701 Jul 05 '12 at 15:55
  • if you are not using any server side script then alternet solution is using get method. so the parameter can be available in the next page. if you are not allowed to use get then there is no other way but use cookie – gaurang171 Jul 05 '12 at 16:45
0

You can use the jQuery.cookie plugin

Its pretty simple to use.

To set a cookie:

$.cookie('cookieName', val, {path: "/", expires: 1})

To get a cookie, I think just:

$.cookie('cookieName');

There's an option to let the cookie last for a session as well instead of number of days as shown in the expires above.

Kayo
  • 966
  • 1
  • 7
  • 16