sindhugauri sindhugauri - 5 months ago 11
HTML Question

JavaScript code not working (unable to read input)

I wrote the following piece of code to read whether the user has entered the login and password fields. However, it is not working. Can someone help me?



function validateForm()
{
var x = document.getElementById("login").innerHTML;
var i;
for(i=0;i<x.length;i++)
{
if( x.elements[i].value==""|| x.elements[i].value=null)
{
alert("Fill in all fields.");
return false;
}
}
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div id="login">
<form role="form" onsubmit="return validateForm()">
<div class="col-sm-offset-8">
<label class="control-label col-sm-8" >Login ID:</label>
<div class="form-group col-sm-8">
<input type="text" class="form-control" id="text" placeholder="Enter login ID">
</div>

<label class="control-label col-sm-8" >Password:</label>
<div class="form-group col-sm-8">
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>

<div class="col-sm-8">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
</div>




Answer

You need to change

<input type="text" class="form-control" id="text" placeholder="Enter login ID">

To

<input type="text" class="form-control" id="login" placeholder="Enter login ID">

The reason being is because your code

document.getElementById("login").value;

is looking for a document element with the ID login but in your markup the element has the ID text, hence your code isn't finding it.

[Edit] As other's have pointed out, you're using .innerHTML - this returns the child HTML nodes of the element being selected. Use .value instead and check that it isn't an empty string, if it's empty then validation fails.