首页 > 解决方案 > Run javascript after input is complete

问题描述

I using javascript to check the length of height input by the user and but the problem I am facing is that even javascript just check the first number of the input and throws an error. Just for eexample if I have to input 45 in the height, I get an error height must be between 6-36 just after entering 4 it doesnt let me enter 5 and when i try to remove move and it input becomes empty It again throws an error height must be between 6-36. Please help me find the problem.

<input type="number" id="message1" name="height" oninput="function_two()">

function function_two() {
    var FrameHeight = document.getElementsByName('height')[0].value;
    if (FrameHeight <= 36 && FrameHeight >= 6) 
        return true;
    else 

    alert("Height must be between 6-36");
  }

标签: javascript

解决方案


您使用了错误的事件 ( input),该事件在向该字段提供任何输入时触发。使用change事件,当值改变并且字段失去焦点时触发。

此外,将 JavaScript 与 HTML 分开。使用现代的、基于标准的实践来处理事件,而不是使用不应使用的内联 HTML 事件属性。

有关使代码更高效和/或将其更新为现代标准的解决方案的其他调整,请参阅下面的评论。

// Get your DOM reference just once. .querySelector() is preferred
// over .getElementsByName, .getElementsByTagName, .getElementsByClassName
// as the former returns a static node list and the latter(s) return 
// live node lists that hurt performance.
let nameInput = document.querySelector("input[name='height']");

// And set up event handlers in JavaScript, not HTML
nameInput.addEventListener("change", rangeCheck);

// Name functions with descriptive names as to what they do.
// Don't use the word "function" in a function name.
function rangeCheck() {
    // In a DOM event handler, you can just use "this" as a reference
    // to the DOM element that triggered the event.
    var FrameHeight = this.value;
    // Just test for the bad values and act accordingly
    if (FrameHeight < 6 || FrameHeight > 36) {
      alert("Height must be between 6-36");
    }
}
<input type="number" id="message1" name="height">


推荐阅读