【问题标题】:Input box validation when there is no input没有输入时的输入框验证
【发布时间】:2017-09-14 07:44:45
【问题描述】:

我正在尝试制作一个简单的计算器。您输入一个号码,然后输入第二个号码,然后按 PLUS 并得到答案提示。如果您在未触摸输入字段时单击加号,我需要显示 alert('no data')

function num1() {
  nm = document.getElementById('nsum1').value;
}

function num2() {
  mn = document.getElementById('nsum2').value;
}

function plus() {
  sum = +nm + +mn;
  if (nm == null || mn == null) {
    alert('no data');
  } else {
    alert(sum);
  }
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />

到目前为止,我已经尝试过 if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "" ) 似乎没有任何效果。

【问题讨论】:

  • 你还没有声明nmmn,当你执行sum = +nm + +mn;这一行时,你的代码会触发一个引用错误,因为你试图转换一些不存在的东西到一个号码。请打开控制台(按 F12)查看错误消息。
  • type="tel"type="number" 太合乎逻辑了。 :)

标签: javascript


【解决方案1】:

如果你没有触摸输入字段并获取值,那么结果将是""

你需要这样的条件

if (nm == "" || mn == "") {
alert('no data');
}

您还应该在验证后进行操作。您正在操作,然后进行验证。


还修复了其他问题。

function plus() {
  mn = document.getElementById('nsum2').value;
  nm = document.getElementById('nsum1').value;
  if (nm == "" || mn == "") {
    alert('no data');
  } else {
    sum = +nm + +mn;
    alert(sum);
  }
}
<input  id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input  id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />

【讨论】:

  • 如果您不触摸输入字段 nm 和 mn 将是未定义的。
  • @Durga 你确定吗?
  • 根据问题 sn-p,nm and mn 在您更改输入之前是未定义的。
  • @Durga True。但问题是 OP 根本不需要更改处理程序。
  • 这是公认的答案,但显示有变量污染全局的代码,我觉得不对。是的,这是 OP 的错误,但即便如此..
【解决方案2】:

你可以更轻松地做到这一点

function plus(num1, num2) {
  alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}

function getNumber(id) {
  return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />

【讨论】:

    【解决方案3】:

    我对您的代码进行了一些更改,以使其更加健壮。有关说明,请参见内联 cmets。

    声明变量 声明你的变量很重要,当你不使用的所有变量都会在全局范围内结束时。当你谷歌这个你会发现很多这样的文章:https://gist.github.com/hallettj/64478

    防止污染全局范围。在小型网站中,这可能不是什么大问题,但在处理大型项目或使用第三方代码时,这是必须的。上面的链接也在某种程度上解释了这一点。

    使用按钮如果您希望某些东西具有交互性,请使用适合它的 HTML 元素。应该使用button 元素,它具有span 所没有的各种辅助功能。例如,默认情况下,当您使用 tab 键导航您的网站时,它将获得焦点。

    使用描述性变量名称 nmmn 现在可能对您来说很重要,但在 6 个月后它将完全是个谜。它还使代码更具可读性,因此更易于维护。

    在 JS 中附加事件监听器 通常,通过 HTML 属性 onXXX="" 分配事件监听器是个坏主意。当您想要更改某些内容时,它更容易出错并且需要更多时间。

    // Wrap your code in a closure to prevent poluting the global scope.
    (function() {
    
      // Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
      var 
        valueA = null,
        valueB = null;
    
      /**
       * To check if your input is a valid number requires a couple of checks.
       * It is best to place these into their own method so you're other
       * method is more readable.
       */
      function isNumber(value) {
        if (
          // == null checks for undefined and null
          value == null ||
          value === '' ||
          isNaN(value)
        ) {
          return false;
        }
    
        return true;
      }
    
      function onChangeHandler(event) {
        var
          // Get the element that dispatched the event.
          target = event.target;
        // Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
        if (!target.classList.contains('js-input')) {
          return;
        }
        // Based on the ID of the target, assign the value to one of the variables for the values.
        switch(target.id) {
        case 'nsum1':
          valueA = parseFloat(target.value);
          break;
          
        case 'nsum2':
          valueB = parseFloat(target.value);
          break;
        }
      }
      
      function onSumTriggerClicked(event) {
        // Check if there are numbers to work with
        if (
          !isNumber(valueA) ||
          !isNumber(valueB)
        ) {
          // If not alert the user
          alert('no data');
          return;
        }
    
        sum = valueA + valueB;
        alert(sum);  
      }
    
      function init() {
        var
          // Get the calculator element.
          calculator = document.getElementById('calculator'),
          // Get the button to sum up the value.
          sumButton = document.getElementById('sum-trigger');
          
        // Add an event listener for the change event.
        calculator.addEventListener('change', onChangeHandler);
        // Add an event listener for the click event.
        sumButton.addEventListener('click', onSumTriggerClicked);
      }
    
      // Call the init method.
      init();
    })();
    <div id="calculator">
      <input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
      <button type="button" id="sum-trigger" id="sum">PLUS</button>
      <input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
    </div>

    【讨论】:

    • 你能详细说明always declare your variables吗?我不这样做,但我想知道你为什么强烈建议这样做。
    • @Keith,谢谢,愚蠢的错字。至于为什么总是声明你的变量,这是一个很好的介绍:youtube.com/watch?v=e1bWoDgRB-8
    • @DouwedeHaan 我对 JS 和 HTML 进行了一些进一步的更改,并更新了我的答案,对更改的内容进行了更多解释。
    • 我认为声明变量意味着您在函数或代码的顶部定义它们(将valueAvalueB 设置为null 的部分)。声明(在你的变量前加上var)是我已经做过的事情了:)谢谢你的解释!
    【解决方案4】:

    尝试通过 Inspector 对其进行跟踪,可能先记录 nm 和 mn 的值,然后相应地纠正您的状况(作为示例)。

    function plus() {
      console.log(nm);
      sum = +nm + +mn;
      if (nm == null || mn == null) {
      alert('no data');
    }
    

    它很可能只是空白。所以在这种情况下,您可以将您的条件修改为:

    if (nm === '' || mn === '') {...}
    

    希望对你有帮助

    【讨论】:

      【解决方案5】:

      请使用this作为参考。

      我已经修复了你的代码。

        if ( num1 === '' && num2 === '' ) {
          alert('no data');
        } else {
          alert( parseInt(num1) + parseInt(num2) );
        }
      

      【讨论】:

      • 是的 ... "TypeError: this.myButton.addEventListener 不是函数"
      • 是的,现在我只填写一个输入时得到NaN
      猜你喜欢
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多