2016-06-08 32 views
-4

下面的代碼在首次運行控制很好,儘管是完全相同的第二控制失敗:JavaScript的 - 無法獲取的未定義或空引用屬性「值」

if (document.getElementById("employeeID").value == "") { 
    document.getElementById("lblEmp").textContent = "Employee Name is required"; 
    ret = false; 
} else { 
    document.getElementById("lblEmp").textContent = ""; 
} 

if (document.getElementById("grossSalary").value == "") { 
    document.getElementById("lblGrossSalary").textContent = "Gross Salary is required"; 
    ret = false; 
} else { 
    document.getElementById('#lblGrossSalary').textContent = ""; 
} 

代碼正在按預期employeeID控制,但拋出主題錯誤的控制grossSalary

剃刀:

<div class="form-group"> 
    @Html.LabelFor(model => model.employeeID, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div id="inner" class="col-md-10"> 
     @Html.EditorFor(model => model.employeeID, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.employeeID, "", new { @class = "text-danger" }) 
     <label id="lblEmp" style="color:red"></label> 
    </div> 
</div> 
<div class="form-group"> 
    @Html.LabelFor(model => model.grossSalary, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div id="inner" class="col-md-10"> 
     @Html.EditorFor(model => model.grossSalary, new { htmlAttributes = new { @class = "form-control"} }) 
     <label id="lblGrossSalary" style="color:red"></label> 
    </div> 
</div> 
+0

什麼是@ Html.LabelFor?這看起來不僅僅是JavaScript和HTML。 – mikemaccana

+0

另外'document.getElementById(「grossSalary」)。value'沒有稱爲'grossSalary'的ID,ID的名字是'lblGrossSalary' – mikemaccana

回答

2

應該

document.getElementById('lblGrossSalary').textContent = ""; 

,而不是

document.getElementById('#lblGrossSalary').textContent = ""; 
在你的上

封鎖其他

1

貌似牛逼他的問題可能是以下幾點:

else { 
    document.getElementById('#lblGrossSalary').textContent = ""; 
} 

變化('#lblGrossSalary')('lblGrossSalary')

0

你只能在對象上使用點(。)運算符,所以如果它的undefined或null,並且想要「.value」,你會得到一個錯誤。

我重新編寫了你的​​代碼,但這應該適合你!它也很多清潔:)

// first save the everything in a variable for later 
// if the element with a given id doen't exist the "|| false" will turn it into a boolean false 
var employeeID = document.getElementById("employeeID") || false; 
var lblEmp = document.getElementById("lblEmp") || false; 
var grossSalary = document.getElementById("grossSalary") || false; 
var lblGrossSalary = document.getElementById("lblGrossSalary") || false; 


// before accessing the .value check if its not false 
if (employeeID && employeeID.value == "") { 
    lblEmp.textContent = "Employee Name is required"; 
    ret = false; 
} 
else { 
    lblEmp.textContent = ""; 
    } 
if (grossSalary && grossSalary.value == "") { 
    lblGrossSalary.textContent = "Gross Salary is required"; 
    ret = false; 
} 
else { 
    lblGrossSalary.textContent = ""; 
} 
相關問題