2017-06-16 38 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沒有包括所有相關的東西。即使我們的兩個答案在有限的背景下都是正確的。