如果用户输入负值,如何在输入字段中使用默认值?

时间:2019-07-16 19:09:40

标签: javascript jquery html

我有一个HTML表单,其输入字段是动态生成的。用户可以手动或使用自动完成功能来填写我的表单输入字段。要使用自动完成功能,用户必须从下拉框中选择任何一个选项,然后自动填写输入字段。通过使用输入字段中的值,我可以执行简单的计算来计算最终值。当用户单击输入字段底部的按钮时,将执行此计算。

一切都很好。但是在测试我的这段代码期间,我发现如果用户在动态生成的输入字段中输入负数或零,则会得到错误值或意外值。花了几个小时后,我发现如果我在输入字段中使用默认值而不是输入值(当用户在输入字段中输入负数或零时可以使用该值),则可以解决该问题。但不幸的是,我无法独自解决这个问题。

有人可以帮我解决这个问题吗?我将非常感谢他。

这是我的代码.....

// define the headings here, so we can access it globally
// in the app
let headings = []

// appending the created HTML string to the DOM
function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
}

// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input type="number" id="${heading}">`
      html += '<br>'
    }
  })

  return html
}

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 3,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using
      // console.log(data)
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});

//calculation for Rating value
$(document).ready(function() {
  $("#Cal").click(function() {
    var peVal = 0,
      roceVal = 0,
      sgVal = 0,
      dyVal = 0;
    jQuery(".fields input").each(function() {
      var idHeading = $(this).attr("id");
      if (idHeading == "PE") {
        peVal = parseInt($(this).val());
      }
      if (idHeading == "ROCE") {
        roceVal = parseInt($(this).val());
      }
      if (idHeading == "SG") {
        sgVal = parseInt($(this).val());
      }
      if (idHeading == "DY") {
        dyVal = parseFloat($(this).val());
      }
    });
    var output = peVal + roceVal + (2 - sgVal) - (4 - dyVal / 2);

    $("output[name='amount']").text(output);
  });
});
<html>

<head>
  <title>Page Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
</head>

<body>
  <div class="ui-widget">
    <form id="frm1">
      <label for="company">Company: </label>
      <input id="company"><br /><br />

      <div class="fields"></div>
      <!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
      <button type="button" id="Cal">Button</button>
      <p>
        <output name="amount" for="calculation">0</output>
      </p>
    </form>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

要获得预期结果,请使用keyup事件并检查负值和零值并将其设置为默认输入值

  1. 使用按键事件并检查每个按键输入的输入值
  2. 对于负值和零值,将输入值更新为默认值

工作代码

var defaultVal = $('input').val();
$('input').on('keyup', function(){
  if($(this).val().indexOf("-") !== -1 || $(this).val() == 0){
    $(this).val($(this).attr('value'))
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="1">

codepen-https://codepen.io/nagasai/pen/orKPwN?editors=1010

带有问题代码段的更新代码

let headings = []
const defaults = {PE: 100, PB: 60, DE: 1, PS: 1};

// appending the created HTML string to the DOM
function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
}

// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input type="number" id="${heading}">`
      html += '<br>'
    }
  })

  return html
}

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 3,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using
      // console.log(data)
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});

//calculation for Rating value
$(document).ready(function() {

  
  $("#Cal").click(function() {
    var peVal = 0,
      roceVal = 0,
      sgVal = 0,
      dyVal = 0;
    $(".fields input").each(function() {
      var idHeading = $(this).attr("id");
      if (idHeading == "PE") {
        peVal = parseInt($(this).val());
      }
      if (idHeading == "ROCE") {
        roceVal = parseInt($(this).val());
      }
      if (idHeading == "SG") {
        sgVal = parseInt($(this).val());
      }
      if (idHeading == "DY") {
        dyVal = parseFloat($(this).val());
      }
    });
    var output = peVal + roceVal + (2 - sgVal) - (4 - dyVal / 2);

    $("output[name='amount']").text(output);
  });
});

  $('body').on('keyup', '.fields input', function(){
  if($(this).val().indexOf("-") !== -1 || $(this).val() == 0){
    $(this).val(defaults[$(this).attr('id')])
  }
})
<head>
  <title>Page Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
</head>

<body>
  <div class="ui-widget">
    <form id="frm1">
      <label for="company">Company: </label>
      <input id="company"><br /><br />

      <div class="fields"></div>
      <!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
      <button type="button" id="Cal">Button</button>
      <p>
        <output name="amount" for="calculation">0</output>
      </p>
    </form>
</body>

codepen- https://codepen.io/nagasai/pen/qzeLje