2016-01-25 28 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