限制输入字段不具有相同的输入

时间:2019-06-27 11:17:00

标签: javascript jquery html

我有一个HTML表,其中有几个输入字段import * as HC_exporting from 'highcharts/modules/exporting';iteNameunitQty

disc%是一个jQuery自动完成字段,因此在选择文本后,焦点将移至ItemName,然后当用户按下Enter键时,我将创建与上面相同的新行

UnitQty列的新行中,我上面也不想要的内容也会出现

我得到的itemname来自JSON数据,因此当用户再次选择之前的数据时,我想提醒您该名称已经存在并清空该字段

我做了什么

ItemNames
"use strict";
console.clear()

function format(number, decimals = 2, locale = 'en-in') {
  const fixed = parseFloat(number).toFixed(decimals);
  const [float, dec] = fixed.split('.')
  const intFormatted = (+float).toLocaleString(locale)
  return intFormatted + (dec ? '.' + dec : '');
}

var CostPrice = "";
var totalAmount = "";
var unitQuantity = 0;
var unitQuantityOnDisc = 0;
var purchaseRateOnDisc = 0;
var purchaseRate = 0;
var totalAmount = "";
var discPercentage = "";
var discAmount = "";
var totalAmountOnDisc = "";
var subTotalOnDisc = 0;
var gstPercentage = "";
var gstAmount = "";
var totalAmountOnGst = "";
var total = 0;
var supplierCode = "";
var totalDiscountAmt = 0;
var totalGstAmt = 0;
var totalUnitQty = 0;
var subtotal = 0;
var totalAfterGrnDisc = 0;
var totalRoundOff = 0;
var totalAfterfreightAmt = 0;
var totalAftercommissionAmt = 0;
var mrpOnDisc = 0;



const tableData = {
  "ALMOND CHBAR~2402": {
    "itemName": "ALMOND CHBAR",
    "itemCode": "2402",
    "costPrice": 20.0,
    "gstPercentage": 14.5,
    "mrp": 30.0
  },
  "A BR SB EX~333": {
    "itemName": "A BR SB EX",
    "itemCode": "333",
    "costPrice": 1.0,
    "gstPercentage": 0.0,
    "mrp": 1.0
  }
}


var autoCompleteData = Object.keys(tableData);

function rowappend(tbody) {

  const markup =
    `<tr>
									  <td>
									    <input type="text" class="form-control commantd" id="itemNametd" name="itemNametd">
									  </td>
									  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd" readonly="readonly"></td>
									  <td>
									    <input type="tel" id="unitQtytd"class="form-control commantd" name="unitQtytd">
									  </td>
									 
									  <td>
									    <input type="tel" id="discPercentagetd"class="form-control commantd" name="discPercentagetd" >
									  </td>
									  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
									  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
									  
									</tr>`

  $(tbody).append(markup);
  setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

  $("[name=itemNametd]", tbody).last().autocomplete({
    source: autoCompleteData

  });
  $("[name=itemNametd]").change(function() {
    if (autoCompleteData.indexOf($(this).val()) == -1) {
      $(this).val("");
      alert("chose correct ItemName")

      return false;
    }
  });

}




rowappend($('tbody', '#tableInvoice'))


function getValues(row) {
  const search = ($('[name=itemNametd]', row).val()).toString()
  const value = tableData[search];
  CostPrice = value.costPrice;

  if (value) {
    $(row).find("[name=itemCodetd]").val(value.itemCode);
    $(row).find("[name=mrptd]").val(format(value.mrp));
    $(row).find("[name=purRatetd]").val(format(CostPrice));
    $(row).find("[name=discAmttd]").val(value.DiscAmt);
    $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
  }

  /*   $("#unitQtytd").click(function () {
   	   $(this).select();
   	}); */
}



function calc(row) {
  unitQuantity = $(row).find("[name=unitQtytd]").val() || '0';
  purchaseRate = $(row).find("[name=purRatetd]").val() || '0';
  var mrp = $(row).find("[name=mrptd]").text() || '0';
  totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));

  $(row).find("[name=totalAmttd]").val(format(totalAmount));

}

function calcDiscount(row) {
  unitQuantityOnDisc = $(row).find("[name=unitQtytd]").val() || '0';
  purchaseRateOnDisc = $(row).find("[name=purRatetd]").val() || '0';
  mrpOnDisc = $(row).find("[name=mrptd]").val() || '0';
  subTotalOnDisc = (parseFloat(unitQuantityOnDisc) * parseFloat(purchaseRateOnDisc));
  discPercentage = $(row).find("[name=discPercentagetd]").val() || '0';
  gstPercentage = $(row).find("[name=gstPercentagetd]").val() || '0';

  discAmount = (parseFloat(discPercentage) / 100) * parseFloat(totalAmount) || 0
  totalAmountOnDisc = (parseFloat(totalAmount) - parseFloat(discAmount))
  gstAmount = (parseFloat(gstPercentage) / 100) * parseFloat(totalAmountOnDisc);
  totalAmountOnGst = (parseFloat(totalAmountOnDisc) + parseFloat(gstAmount))
  total += parseFloat(totalAmountOnGst);
  totalDiscountAmt += parseFloat(discAmount);
  totalGstAmt += parseFloat(gstAmount);
  totalUnitQty += parseFloat(unitQuantity);
  subtotal += parseFloat(subTotalOnDisc);
  totalRoundOff = total - Math.round(total);


  $(row).find("[name=discAmttd]").val(format(discAmount));
  $(row).find("[name=gstAmttd]").val(format(gstAmount));
  $(row).find("[name=totalAmttd]").val(format(totalAmountOnGst));

  $("#unitQtytf").text(format(totalUnitQty));
  $("#discAmttf").text(format(totalDiscountAmt));
  $("#gstAmttf").text(format(totalGstAmt));
  $("#netAmtInput").val(format(total));
  $("#totalAmttf").text(format(total));
  $("#subTotalInput").val(format(subtotal));
  $("#itemAmtDiscinput").val(format(totalDiscountAmt));
  $("#taxAmtInput").val(format(totalGstAmt));
  //	  $("#roundOffAmtInput").val(format(totalRoundOff));


}

$(document).on('focusout', (e) => {


  const row = e.target.parentElement.parentElement
  if (e.target.matches("[name=itemNametd]")) { // whene focus is out from itemNametd

    getValues(e.target.parentElement.parentElement)

  }

});

$(document).keypress(function(event) { // here I am trying to create new row when enter is clicked
  const row = event.target.parentElement.parentElement
  var keycode = event.keyCode || event.which;
  if (keycode == '13') {
    alert("presed")
    calcDiscount(event.target.parentElement.parentElement)
    if ($(row).parent().find('tr').length - $(row).index() === 1) {
      rowappend(event.target.parentElement.parentElement.parentElement)

      total = 0;
      totalDiscountAmt = 0;
      totalGstAmt = 0;
      totalUnitQty = 0;
      subtotal = 0;

      $("#tableInvoice tbody tr").each(function() {
        calc(this)
        calcDiscount(this)
      })
    }
  }



});
document.addEventListener("keydown", function(e) {

  const row = e.target.parentElement.parentElement
  if (event.target.matches('[name=discPercentagetd]') || e.target.matches('[name=unitQtytd]')) {

    var keycode = e.keyCode || event.e;
    if (keycode == '9') {


      if (!$(event.target).val()) {
        e.preventDefault();
        return;
      }


      total = 0;
      totalDiscountAmt = 0;
      totalGstAmt = 0;
      totalUnitQty = 0;
      subtotal = 0;

      $("#tableInvoice tbody tr").each(function() {
        calc(this)
        calcDiscount(this)
      })


    }

  }


});

fiddle Link

2 个答案:

答案 0 :(得分:2)

您需要创建一个包含所有商品名称的数组,并检查输入的值在该数组中是否存在。

将文本框名称itemNametd更改为itemNametd[]

jQuery代码

var itemNametd=[];var flag=  'Success';var Message="Success";
   $('input[name="itemNametd[]"]').each(function() {
        $(this).css("border", "");
        if ($(this).val() == '') {
            $(this).css("border", "1px solid red");
            flag = 'Error';
             Message="Please Enter Value"
        }else{
        if ($.inArray($(this).val(), itemNametd) != -1){
         $(this).css("border", "1px solid red");
         $(this).val('')
           Message="name is already present"
   flag = 'Error';
                        }else{
            itemNametd.push($(this).val())
            }

        }
    })

    if(flag=='Error'){
    alert(Message)
    return false
    }

选中此Fiddel

答案 1 :(得分:0)

  • 您可以维护一个ItemName数组。因此,当用户按下Enter键时 按钮,进行功能调用,检查是否输入了ItemName 已存在于列表中。
  • 如果数组中已经存在ItemName,则向用户显示错误。
  • 如果没有ItemName,则将其添加到数组列表中。