2017-06-16 41 views
0

我遇到了用javascript更改跨度文本的问题。我正在尝试在提交错误的输入时出现错误消息。我怎样才能解决这个问题?用js更改跨度文本

 function SubmitFunc() { 
 
      var studentNameInput = document.getElementById("student-name"); 
 
      CheckInputLetters(studentNameInput); 
 

 
     } 
 
     function CheckInputLetters(input) { 
 
      if (!/^[a-zA-Z_ ]+$/.test(input.value)) { 
 
       document.getElementById("name-error").innerHTML = "error"; 
 
      } 
 
     }
<label class="data-lbls data-titles-dec">FullName</label> 
 
    <input class="input-style" type="text" id="student-name" placeholder="Enter Full Name" /> 
 
    <span id="name-error" style="float:right;"></span>

+0

代码看起来不错。问题必须与表单提交和刷新页面相关联,从而失去了要添加到所述跨度的文本。或者其他不包含在问题中的其他内容。 –

+0

我尝试在更改后提醒量程的值。该警报显示新值,但在页面中根本没有改变。 –

+0

这并不反驳我的理论。 –

回答

0

这是关于包含窗体标签和输入提交。当提交输入刷新页面时,所有更改都会重新设置。我将type="submit"更改为type="button"。现在它工作

-2

你需要通过一些参考方法类似的onblur在输入字段:

 function SubmitFunc() { 
 
      var studentNameInput = document.getElementById("student-name"); 
 
      CheckInputLetters(studentNameInput); 
 
     } 
 
     function CheckInputLetters(input) { 
 
      if (!/^[a-zA-Z_\s]+$/.test(input.value)) { 
 
       document.getElementById("name-error").innerHTML = "error"; 
 
      } 
 
     }
<label class="data-lbls data-titles-dec">FullName</label> 
 
    <input class="input-style" onblur="SubmitFunc();" type="text" id="student-name" placeholder="Enter Full Name" /> 
 
    <span id="name-error" style="float:right;"></span>

+0

我很高兴我得到了downvoted的东西,实际工作:http://soulglo.com/what/44595682.html – geeves

-1

如果表单提交,页面会重新加载,你不会看到更改(错误信息)。您可以使用函数的返回值,以防止表单提交,如果有任何验证错误:

function SubmitFunc() { 
 
    var studentNameInput = document.getElementById("student-name"); 
 
    return CheckInputLetters(studentNameInput); 
 
} 
 

 
function CheckInputLetters(input) { 
 
    if (!/^[a-zA-Z_ ]+$/.test(input.value)) { 
 
    document.getElementById("name-error").innerHTML = "error"; 
 
    return false; // error 
 
    } 
 
    return true; // no error 
 
}
<form id="some" onsubmit="return SubmitFunc()"> 
 
    <label class="data-lbls data-titles-dec">FullName</label> 
 
    <input class="input-style" type="text" id="student-name" placeholder="Enter Full Name" /> 
 
    <span id="name-error" style="float:right;"></span> 
 
    <button type="submit">Send</button> 
 
</form>

+0

为什么downvote? – luisenrike

0

luisenrike,这是因为OP没有包括所有相关的东西。即使我们的两个答案在有限的背景下都是正确的。