1
\$\begingroup\$

I wrote this code to check if a text box is empty. If it is I put the current date into it with a score and loop over the six boxes.
Once it fills the boxes it will then loop over checking the dates and it finds the oldest and overrides it with the new value.

I feel what I have done here may be a bit crude and or long winded, this there a better way I could have done this?

<input type="textbox" id="bank1" value="19990112" class="bank" /> 1
<br>
<input type="textbox" id="bank2" value="19980112" class="bank" /> 2
<br>
<input type="textbox" id="bank3" value="19970112" class="bank" /> 3
<br>
<input type="textbox" id="bank4" value="19960112" class="bank" /> 4
<br>
<input type="textbox" id="bank5" value="19950112" class="bank" /> 5
<br>
<input type="textbox" id="bank6" value="19940112" class="bank" /> 6
<br>

<input type="button" value="Click Me" id="btn" />


var idAndValues = {};
var Time = [];
var oldest = "";
var formatDateMili = "";
var ids = "";
var m = false;
var now = new Date();
var a = now.getFullYear();
var b = now.getMonth();
var c =now.getDate();
var FullDateNow = a.toString() + "0"+b.toString() + c.toString();


$('#btn').click(function() {



  $('.bank').each(function() {


    if ($(this).val() != "") {

      var StoredDate = $(this).val();
      var formatDateMili = DateStringSort(StoredDate).getTime();
      Time.push(formatDateMili);
      ids = $(this).attr('id');
      idAndValues[ids] = formatDateMili;

    } //end if 


    if ($(this).val() === "") {

      $(this).val("19980214" + "_" + "score");
      m = true;

      return false;

    } else {

      m = false;
    }


  }); // end loop 







  if (m != true) {
    oldest = Math.min.apply(null, Time);

    for (var key in idAndValues) {
      if (idAndValues.hasOwnProperty(key)) {


        //   alert(idAndValues[key]+ " key checking" + " oldest checking "+ oldest);
        if (idAndValues[key] === oldest) {
          $('#' + key).val(FullDateNow + "_" + "score");
          Time = [];

        }


        //   alert(key + " -> " + idAndValues[key]);
      }
    }








  }






});








function DateStringSort(Stored) {

  var StoredDayTrim = Stored.substring(6, 8);

  var StoredmonthTrim = Stored.substring(4, 6);

  var StoredYearTrim = Stored.substring(0, 4);

  var FormatDate = new Date(StoredYearTrim, StoredmonthTrim, StoredDayTrim);

  return FormatDate;


}

here is a fiddle

\$\endgroup\$
  • \$\begingroup\$ Instead of only using a fiddle, you might also want to use the power of Stack Snippets. That's just like a fiddle but embedded on Stack Exchange. \$\endgroup\$ – Simon Forsberg Jan 29 '16 at 21:04
  • \$\begingroup\$ oh ok cool thanks will do, still very to this. Many thanks. \$\endgroup\$ – Mo Star Jan 29 '16 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.