2016-01-25 27 views
0

我想在文本框的空白處顯示「無效名稱」。 這裏是我的JavaScript代碼來檢查然而,沒有顯示如何檢查文本框是否爲空,只要我將它留在JavaScript中

function checkName(field) { 
      var mystring = document.getElementById('na2').value; 
      if (mystring===""||mystring==""||mystring==null||mystring==undefined) { 
       document.getElementById('na1').innerHTML = 'Invalid!!!!!!!' 
      } 
     } 

「無效信息」,「空的名字」。

+0

更換'如果(MyString的=== 「」 ||了mystring == 「」 | mystring == null || mystring == undefined)帶有if(mystring ==「」|| mystring == null || mystring == undefined)'.Edit:在@DanielHigueras指出錯誤後糾正。 –

+0

什麼是na1和na2?你有分配給一個事件的功能嗎? –

+0

@SatejS你有兩次mystring ==「」。 –

回答

0

您可以使用

function checkTextField() { 
    if (document.getElementById('na2').value == '') { 
     document.getElementById('na1').innerHTML = 'Invalid'; 
    } 
} 

function checkTextField() { 
    if (!document.getElementById('na2').value) { 
     document.getElementById('na1').innerHTML = 'Invalid'; 
    } 
} 

工作例如:https://jsfiddle.net/8c6v1xk5/4/

+0

我相信他希望在html標記中顯示文本,而不是作爲警報 –

0
function checkTextField() 
{ 
    // if there's no value entered within the textbox 
    if (!document.getElementById('na2').value) 
    { 
     // Change the inner html of the error element from "" to invalid 
     document.getElementById('na1').innerHTML = 'Invalid'; 
    } 
    // otherwise there must be data present 
    else 
    { 
     // Remove the inner html and re-set it to an empty string 
     document.getElementById('na1').innerHTML = ''; 
    } 
} 
+1

您的回答可能是正確的,但請解釋此代碼如何回答問題,以便將來的搜索者可以瞭解背後的原因。 – SnareChops

+0

我已經更新了我的答案 – STORM