验证后为什么输入值不确定?

时间:2019-02-28 17:13:46

标签: javascript

我有一个似乎无法解决的简单问题。我只希望能够在输入名称并单击提交后显示输入名称字段的值。但是,似乎会发生未定义的情况。

有人可以解释为什么会发生这种情况以及如何解决吗?代码如下:

var tmp;

function test() {
  if (!tmp) {
     // save the current foo for the first call of test
    tmp = foo
  } else {
    // the comparison of the current foo with tmp (the previous foo) is false
    console.log(tmp == foo)
  }

  function foo() {}
}

test()
test()
var name = document.querySelector('#withJS input:first-of-type'),
    date = document.querySelector('#withJS input:not(:first-of-type)'),
    errorMsg = document.querySelector('#withJS .errorMsg');
  
  errorMsg.style.display='none';

  function validateForm() {
    alert(name.value);
    /*
    if(name.length == 0){
    errorMsg.style.display='block';
      errorMsg.textContent='Enter Name';
    }
    */
  }
#noJS, #withJS {
  background: lightgreen;
  max-width: 300px;
  padding: 10px;
  border: 5px solid #ccc;
}
#withJS {
  background: lightblue;
  margin-top: 10px;
}

.errorMsg {
  background: red;
  padding: 10px;
  margin-top: 10px;
  color: #fff;
  text-transform: uppercase;
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您已声明的全局变量namewindow属性name发生了冲突。更改该变量的名称,即fname

var fname = document.querySelector('#withJS input:first-of-type'),
    date = document.querySelector('#withJS input:not(:first-of-type)'),
    errorMsg = document.querySelector('#withJS .errorMsg');
  
  errorMsg.style.display='none';

  function validateForm() {
    alert(fname.value);
    /*
    if(name.length == 0){
    errorMsg.style.display='block';
      errorMsg.textContent='Enter Name';
    }
    */
  }
#noJS, #withJS {
  background: lightgreen;
  max-width: 300px;
  padding: 10px;
  border: 5px solid #ccc;
}
#withJS {
  background: lightblue;
  margin-top: 10px;
}

.errorMsg {
  background: red;
  padding: 10px;
  margin-top: 10px;
  color: #fff;
  text-transform: uppercase;
}
<div id='withJS'>
<form>
Name:<br>
<input type="text">
  <br>
  Date:<br>
<input type="date">
  <br><br>
  <input type="submit" value="Submit" onclick='validateForm()'>
</form>
  <div class='errorMsg'>error message here</div>
</div>