Javascript表单验证事件

时间:2016-11-25 20:16:42

标签: javascript html forms

我正在尝试使用Javascript验证表单,我希望在字符串长度为一定数量的字符时更新范围

 getStats <- function(data,col) {
   ## if you want to pass a string argument instead, remove
   ## the next line
   col <- deparse(substitute(col))
   funs <- c("n","mean","stats::median","sd","se")
   dots <- c(sprintf("sum(!is.na(%s))",col),
      sprintf("%s(%s,na.rm=TRUE)",funs[2:4],col),
      "sd/sqrt(n)")
   names(dots) <- gsub("^.*::","",funs)  ## ugh
   summarise_(data,.dots=dots)
}

x %>% group_by(year,phase) %>% getStats(doy)

2 个答案:

答案 0 :(得分:1)

变量范围很重要。

npm install pm2 ./node_modules/.bin/pm2 start server.js 内,你声明了三个变量......并且只使用window.onload一次,为name分配一个值。

onkeyup内使用validate,即a global variable already provided by the browser(它不是您声明的另一个函数的本地变量)。这是一个字符串,因此它的长度永远不会改变。

&#13;
&#13;
name
&#13;
// Create an IIFE to create a new (non-global) scope for all your variables.
(function() {

  // Declare your variables at a level all the functions can reach them
  var spanName, name;

  // Get the DOM elements when the load event fires
  function getDomElements() {
    name = document.getElementById("contact").elements.name;
    spanName = document.getElementById("spanName");

    name.addEventListener("keyup", validate);
  }

  window.addEventListener("load", getDomElements);

  // Define your validation function
  // Check the VALUE of the form control, not the form control itself
  function validate() {
    // Make sure you exclude values you want a later condition to match
    if (name.value.length > 0 & name.value.length <= 8) {
      spanName.innerHTML = "&#10004;";
    } else if (name.value.length > 8) {
      spanName.innerHTML = "name is to long";
    } else {
      spanName.innerHTML = "yolo";
    }
  }
})();
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对不起,这是一个答案:

var contact, spanName;
window.onload = function () {
    spanName = document.getElementById("spanName");
    contact = document.getElementById("name");
    contact.onkeyup = validate;
}
function validate() {
    var name = contact.value;
    var length = name.length;
    if (length > 0 && length <=8) {
        spanName.innerHTML = "&#10004;";
    } else if (length > 8) {
        spanName.innerHTML = "name is to long";
    } else {
        spanName.innerHTML = "yolo";
    }
}

对你有用吗?