简体   繁体   English

防止用户在数字类型的输入元素中输入负数

[英]Preventing user from entering negative numbers in input elements with number type

I have got the following code from another question on here on how to prevent users from entering negative numbers, however it covered all inputs. 我在这里有关于如何防止用户输入负数的另一个问题的以下代码,但它涵盖了所有输入。 I have 2 number type input elements and 2 text type input elements. 我有2个number类型输入元素和2个text类型输入元素。 I obviously want to allow the user to add any character to the text fields but want to prevent users entering negative numbers/non number content to the number inputs. 我显然希望允许用户在文本字段中添加任何字符,但希望阻止用户输入负数/非数字内容到number输入。

My code below works for one input with the number type and not the other. 我的下面的代码适用于一个输入number类型而不是另一个输入。 How would I go about changing my code to allow it for the other number input? 如何更改我的代码以允许其他number输入? Any help would be greatly appreciated. 任何帮助将不胜感激。

HTML HTML

<div class="cpNewTemplateDetailsWrap">
    <div class="col-sm-3">
        <label>Course Id</label>
    </div>
    <div class="col-sm-9">
        <input id="courseIdInput" type="text" class="form-control input-lg" placeholder="e.g. CT001" />
    </div>
    <div class="col-sm-3">
        <label>Course Description</label>
    </div>
    <div class="col-sm-9">
        <input id="courseDescInput" type="text" class="form-control input-lg" placeholder="e.g. Cadet Training" />
    </div>
    <div class="col-sm-3">
        <label>Course Duration <small>(Days)</small>
        </label>
    </div>
    <div class="col-sm-9">
        <input id="courseDurationInput" type="number" min="0" class="form-control input-lg" placeholder="5" />
    </div>
    <div class="col-sm-3" id="courseDemandTitle">
        <label>Course Demand</label>
    </div>
    <div class="col-sm-9">
        <input id="courseDemandInput" type="number" min="0" class="form-control input-lg" placeholder="5" />
    </div>
</div>

Javascript 使用Javascript

var myInput = document.querySelectorAll("input[type=number]")[0];
myInput.addEventListener('keypress', function(e) {
  var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
  function keyAllowed() {
    var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50,
                51,52,53,54,55,56,57,91,92,93];
    if (key && keys.indexOf(key) === -1)
      return false;
    else
      return true;
  }
  if (!keyAllowed())
    e.preventDefault();
}, false);

// Disable pasting of non-numbers
myInput.addEventListener('paste', function(e) {
  var pasteData = e.clipboardData.getData('text/plain');
  if (pasteData.match(/[^0-9]/))
    e.preventDefault();
}, false);

JS Fiddle Here! JS小提琴!

Edit 编辑

With some of the duplicate questions, they cover just one input or all inputs. 对于一些重复的问题,它们只涵盖一个输入或所有输入。 I just want to prevent negative numbers of 2 inputs. 我只是想防止2个输入的负数。 And if I wanted to add more input elements with a number type, I don't want to repeat code for each iteration. 如果我想添加更多带number类型的输入元素,我不想为每次迭代重复代码。 For example if I had 12 more inputs, I don't want to use that code 12 more times. 例如,如果我有12个输入,我不想再使用该代码12次。

You were only adding the event listeners to the first number input. 您只是将事件侦听器添加到第一个数字输入。

https://jsfiddle.net/tpsbnp9q/5/ https://jsfiddle.net/tpsbnp9q/5/

var myInput = document.querySelectorAll("input[type=number]");

function keyAllowed(key) {
  var keys = [8, 9, 13, 16, 17, 18, 19, 20, 27, 46, 48, 49, 50,
    51, 52, 53, 54, 55, 56, 57, 91, 92, 93
  ];
  if (key && keys.indexOf(key) === -1)
    return false;
  else
    return true;
}

myInput.forEach(function(element) {
  element.addEventListener('keypress', function(e) {
    var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
    if (!keyAllowed(key))
      e.preventDefault();
  }, false);

  // Disable pasting of non-numbers
  element.addEventListener('paste', function(e) {
    var pasteData = e.clipboardData.getData('text/plain');
    if (pasteData.match(/[^0-9]/))
      e.preventDefault();
  }, false);
})

Your querySelectorAll method returns an array of all input elements of type number. 您的querySelectorAll方法返回数字类型的所有输入元素的数组。 You currently have the first element in the array selected, so that's the only input box that is checking for inputs. 您当前在所选数组中有第一个元素,因此这是检查输入的唯一输入框。

The code that is causing only one input to be limited is the [0] at the end of this line 仅导致一个输入受限的代码是此行末尾的[0]

var myInput = document.querySelectorAll("input[type=number]")[0];

Now you could have a second variable, say myOtherInput, and add an event listener to that too: 现在你可以有一个第二个变量,比如myOtherInput,并为它添加一个事件监听器:

var myOtherInput = document.querySelectorAll("input[type=number]")[1];
myOtherInput.addEventListener('keypress', function(e) {
  var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
  function keyAllowed() {
    var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50,
                51,52,53,54,55,56,57,91,92,93];
    if (key && keys.indexOf(key) === -1)
      return false;
    else
      return true;
  }
  if (!keyAllowed())
    e.preventDefault();
}, false);

But it would add repeated code and might not help you if you wanted to limit loads of inputs. 但它会添加重复的代码,如果您想限制输入的负载,可能无法帮助您。

您可以为所有选择性输入元素指定类名,并使用循环在每个输入[type ='number']上附加事件。

  1. Get all your number fields. 获取所有数字字段。
  2. Add keypress listener to each element and if the key pressed is zero don't add it. 将keypress侦听器添加到每个元素,如果按下的键为零,则不添加它。

This doesn't cover the case for pasting negative numbers. 这不包括粘贴负数的情况。

 // get all number fields var numInputs = document.querySelectorAll('input[type="number"]'); // Loop through the collection and call addListener on each element Array.prototype.forEach.call(numInputs, addListener); function addListener(elm,index){ elm.setAttribute('min', 0); // set the min attribute on each field elm.addEventListener('keypress', function(e){ // add listener to each field var key = !isNaN(e.charCode) ? e.charCode : e.keyCode; str = String.fromCharCode(key); if (str.localeCompare('-') === 0){ event.preventDefault(); } }); } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <lable>Number: <input type="number"></label> <br> <lable>Number: <input type="number"></label> <br> <lable>Text: <input type="text"></label> <br> <lable>Text: <input type="text"></label> </body> </html> 

Usually just using the min="0" attribute on a type="number" field should be enough. 通常只在type="number"字段上使用min="0"属性就足够了。

<input type="number" min="0" step="0.1" name="whatever" />

If you need to stick to <input type="text" /> or support very old browsers or want to make sure users dont enter negative numbers via keyboard (possible with min="0" on some browsers), with jQuery you can overwrite negative values on focusOut for all inputs having a specific class attribute with the following code: 如果您需要坚持<input type="text" />或支持非常旧的浏览器或想要确保用户不通过键盘输入负数(在某些浏览器上可能使用min="0" ),使用jQuery可以覆盖具有特定类属性的所有输入的focusOut上的负值,具有以下代码:

$(document).ready(function(){
    $("body").on('focusout', '.my-input-number-positive', function(){
        if($(this).val() < 0){
            $(this).val('0'); // alternatively show a hint – or whatever
        }
    });
});

This does not replace server side validation! 这不会取代服务器端验证!

You can use js directly on input - I think this is the simple and clean solution for your problem: 您可以直接在输入上使用js - 我认为这是解决您问题的简单而干净的解决方案:

just put this on each input: onkeypress='return event.charCode >= 48 && event.charCode <= 57' 只需将它放在每个输入上: onkeypress='return event.charCode >= 48 && event.charCode <= 57'

https://jsfiddle.net/tpsbnp9q/3/ https://jsfiddle.net/tpsbnp9q/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM