根据到期日计算输入字段

时间:2018-04-20 23:57:21

标签: javascript jquery

包含50个条目的表单:每个表单包含P1-48,E1-48和X1-48。我想计算入场费" E1"基于到期日期X1。到期日的js日期格式为YYYY.MM.DD,例如。 2018.04.21并且如果玩家的到期日期大于或等于今天的日期,则玩家支付3美元。如果他的到期日期较早或低于今天的日期,他将支付5美元。但如果到期日期为空白并且玩家支付会员费,则免收入场费为零。

JS:

<script src = "js/moment.min.js"></script>

我也将此作为&#34;模板&#34;开始指南。我认为它可以被修改并将目标结果搭载到它上面。

<script> // change expiration date color
function getExpireDate(ele) {
var i = null;
for (i = 0; members.length > i; i++) {
    if (members[i].Name == ele.value) {
        var exDate = moment(members[i].Expires, 'YYYY.MM.DD');
        if (moment().isAfter(exDate)) {
        $(ele).closest('.universal').find('.expDate').css('color', "#A3005B");
        } else {
        $(ele).closest('.universal').find('.expDate').css('color', "#275052");
        }
        return members[i].Expires;
     }
}
return '';
}
</script>

<script>

for (let i = 0; i <= 48; i++) {
    $("#P" + i).on("blur", function(){
    $("#X" +i).val(getExpireDate(this));
    });
}
</script>

<script>

    var members [
    {"Name": "Jones, David", "Expires": "2017.05.03" },
    {"Name": "Roth, Bill", "Expires": "2017.03.08" },
    {"Name": "Scullin, Kenn", "Expires": "2019.02.20" }
    ]

<script>

HTML:

<div>
    <input type = "text" id = "P1"> <!--Player-->
    <input type = "text" id = "E1"> <!--Entry Fee--> 
    <input type = "text" id = "M1"> <!--Membership Fee--> 
<input type = "text" id = "X1" onblur="getExpireDate()" class="expDate"> <!--expires-->
<div>

有趣的是:

<input type = "text" onblur="getClass()" class="text" id="Y1" maxlength = "4" size = "4" disabled /> <!--works even with input disabled -->

<input type = "text" onblur="calcEntryFee(this);" class="expDate" name = "exp" id="X1" maxlength = "10" size = "10" disabled /><!--new code doesn't work -->

<script> // Lookup class or rating

function getClass(ele) {
var i = null;
for (i = 0; members.length > i; i++) {
if (members[i].Name == ele.value) {
return members[i].Rating;

}
}
return;
}


for (let i = 0; i <= 48; i++) {
$("#P" + i).on("blur", function(){
$("#Y" +i).val(getClass(this));
});
}
</script>

3 个答案:

答案 0 :(得分:4)

这个怎么样:

(主functioncalcEntryFee()。)

var members = [
  // ... fill data here.
];

function getMemberData( name ) {
    var a = jQuery.trim( name ).toLowerCase(),
        i, b, member;

    for ( i = 0; i < members.length; i++ ) {
        b = jQuery.trim( members[ i ].Name ).toLowerCase();
        if ( a === b ) {
            member = members[ i ];
            break;
        }
    }

    return member || {};
}

function calcEntryFee( elem ) {
    var idx, member, exDate, today, fee;

    elem = elem || {};
    if ( /^[PEMX](\d+)$/.test( elem.id ) ) {
        idx = RegExp.$1;
    } else {
        return false;
    }

    member = getMemberData( jQuery( '#P' + idx ).val() );
    mmfee = parseFloat( jQuery( '#M' + idx ).val() );
    exDate = moment( member.Expires, 'YYYY.MM.DD' );
    today = moment();
    fee = '';

    if ( exDate.isBefore( today ) ) {
        fee = 5;
    } else if ( exDate.isSameOrAfter( today ) ) {
        fee = 3;
    } else if ( ! member.Expires && mmfee > 0 ) {
        fee = 0;
    }

    // Updates the entry fee input value.
    jQuery( '#E' + idx ).val( fee );

    return fee;
}

您可以像这样使用calcEntryFee()

<input id="X1" placeholder="X" size="10" onblur="calcEntryFee( this );" />

查看完整代码并https://codepen.io/anon/pen/WJRNVY 上尝试现场演示。

<强>更新

由于到期日期字段/ input 已停用,请改为使用此字段:(注意id值,也可以是P2P3等等。)

<input id="P1" placeholder="P" onblur="calcEntryFee( this );" />

即。将calcEntryFee( this );添加到&#34;播放器&#34;的onblur属性字段和不是到期日期字段。或者将其添加到未禁用的任何同级/相关字段,或者我们可以标记为的字段。 (这样我们就可以专注于&#34;取消焦点&#34;或模糊字段,然后浏览器会调用附加到字段calcEntryFee( this );的{​​{1}}事件。)

尝试现场演示:https://codepen.io/anon/pen/xjgQyx

或者,您可以在不使用blur /字段的 onblur属性的情况下添加 :(请参阅您提供的代码你的问题)

input

答案 1 :(得分:2)

不得不重新阅读你的问题几次。我仍然不确定你完全理解你想要实现的目标,但我相信这非常接近:

let getMember = {
  index: function(name) {
    let index = -1;
      $.each(members, function(i, player) {
      if (player.Name === name) { index = i; }
    });
    return index;
  },
  entryFee: function(memberIndex) {
    if (memberIndex === -1) {
      return 'waived';
    } else {}
      let today = new Date();
      let expires = new Date(members[memberIndex].Expires.replace(/\./g, '-'));
      return today <= expires ? '$3' : '$5';    
    }
};

let members = [
  {"Name": "Jones, David", "Expires": "2017.05.03" },
  {"Name": "Roth, Bill", "Expires": "2017.03.08" },
  {"Name": "Scullin, Kenn", "Expires": "2019.02.20" }
];


let tableHTML = '';

for (let i=0; i < 50; i++) {
    tableHTML += `
  <div class="row">
    <input type="text" class="player" placeholder="player">
    <input type="text" class="entryFee" placeholder="entry fee">
    <input type="text" class="membershipFee" placeholder="membership fee">
    <input type="text" class="expDate" placeholder="expire date">
  <div>`;
}

$(`<div class="table">${tableHTML}</div>`)
  .appendTo('body')
  .on('blur', '.player', function() {
    if (!this.value) { return false; }
    let memberIndex = getMember.index(this.value);
    let entryFee = getMember.entryFee(memberIndex);

    $(this)
      .next().val(entryFee)
      .next().val(entryFee === 'waived' ? 'yes' : 'no')
      .next()
        .val(memberIndex >= 0 ? members[memberIndex].Expires : 'non-member')
        .addClass(entryFee === '$3' ? 'currentMember' : 'nonCurrentMember');

    $('.player').eq($('.player').index(this) + 1).focus();
});

https://jsfiddle.net/ypzjfkxk/

没有外部库来启动!不能说我对moment.js有任何经验,但我遇到的所有问题似乎都可以通过简单的javascript解决。此外,为此生成一个字母表也同样快速和容易。然后你不必担心播放器输入中的拼写错误。除非您尝试创建日志或其他内容?

答案 2 :(得分:1)

这对我有用:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>



    <script type="application/javascript">
      var members = [
        {"Name": "Jones, David", "Expires": "2017.05.03" },
        {"Name": "Scullin, Kenn", "Expires": "2019.02.20" },
        {"Name": "Peter, Kenn", "Expires": "2018.04.24" },
        {"Name": "Chris, Kennx", "Expires": "" }
      ];

      $(document).ready(function(){
        var nUsers = 4; // Number os users

        // Fill inputs (tmp: visual purpose)
        for (count=1; count<=nUsers; count++){
          $("#P"+count).val(members[count-1].Name);
          $("#X"+count).val(members[count-1].Expires);
        }
        $("#M4").val("$20");

        /* Get current date. For security purpose you should
          get this from the server and not the client side.*/
        var date = moment().toDate();

        // Go through every input row
        for (count=1; count<=nUsers; count++){
          var exDate = $("#X"+count).val(); // Get the exire date

          // Confirm that date is has the right format
          if (moment(exDate, 'YYYY.MM.DD').isValid()){
            exDate = moment(exDate, 'YYYY.MM.DD').toDate();
            var diff = new Date(exDate - date);
            var nDays = parseInt(diff/1000/60/60/24);

            console.log(nDays);

            if (nDays >= 0){ // If his expires date is greater or equal to today's date
              $("#E"+count).val("$3");
              $("#X"+count).css('color', "#275052");
            }
            if (nDays < 0){
              $("#E"+count).val("$5"); // If his expires date is older or less than today's date
              $("#X"+count).css('color', "#A3005B");
            }
          }
          else{ // If expire date is empty
            var mFee = parseFloat($("#M"+count).val().replace(/\$/, ''));
            if ((exDate.length == 0) && (mFee > 0 )){ // If the expires date is blank and the player pays a membership fee
              $("#E"+count).val("$0");
            }
          }
        }
      });
    </script>

  </head>
  <body>

    <!-- visual purpose -->
    <div>
      <input type = "text" id = "P1"> <!--Player-->
      <input type = "text" id = "E1"> <!--Entry Fee-->
      <input type = "text" id = "M1"> <!--Membership Fee-->
      <input type = "text" id = "X1" class="expDate"> <!--expires-->

      <br>

      <input type = "text" id = "P2"> <!--Player-->
      <input type = "text" id = "E2"> <!--Entry Fee-->
      <input type = "text" id = "M2"> <!--Membership Fee-->
      <input type = "text" id = "X2" class="expDate"> <!--expires-->

      <br>

      <input type = "text" id = "P3"> <!--Player-->
      <input type = "text" id = "E3"> <!--Entry Fee-->
      <input type = "text" id = "M3"> <!--Membership Fee-->
      <input type = "text" id = "X3" class="expDate"> <!--expires-->

      <br>

      <input type = "text" id = "P4"> <!--Player-->
      <input type = "text" id = "E4"> <!--Entry Fee-->
      <input type = "text" id = "M4"> <!--Membership Fee-->
      <input type = "text" id = "X4" class="expDate"> <!--expires-->

    <div>

  </body>
</html>
&#13;
&#13;
&#13;

我在代码中给你的建议是你应该从服务器端而不是从客户端获得当前时间。

我希望这对你有用。 :)