Saurabh Shukla
Saurabh Shukla

Reputation: 57

JS Form validation issue

I am new to JS ! This is my first program. It validates that the text field shouldn't be null. I tried everthing but nothing seems to work.

<script type="text/javascript">
    var data_age = document.getElementById("ages") ;

    function check() {
        if (data_age==null) {
            alert("no data") ;
            return false ;
        } else {
            return true ;
        }   
    }
</script>


<form name="frm" action="a.php" method="post" onsubmit="return check(this)">
<input type="text" name="age" id="ages">
<input type="submit" value="submit">
</form>

Upvotes: 2

Views: 101

Answers (3)

swemon
swemon

Reputation: 5946

You should add var data_age = document.getElementById("ages") ; inside function.

 function check()
        {
            var data_age = document.getElementById("ages") ;
            if (data_age.value == "")
            {
            alert("no data") ;
            return false ;
            }  
        }

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

If a variable contains a text field, it is never equal to null for the exact reason it is a text field. (getElementById can return null in case the element does not exist, though.) You want to check whether its value is empty or not. You can use data_age.value === "" for that (getting the value and comparing it against the empty string).

Second, you call getElementById before you define the element in HTML. You could swap the <form> and <script> elements so that the element is there at the time you call getElementById. Also, use var data_age = ....

Upvotes: 4

Pedro Pep&#234;
Pedro Pep&#234;

Reputation: 123

Try this

<script type="text/javascript">

    var isBlank = function (str) {
        return str == null || str.trim().length == 0;
    }

function check()
{

var data_age = document.getElementById("ages") ;
if (isBlank(data_age.value))
{
alert("no data") ;
return false ;
}
else
{
return true ;
}   
}
</script>


<form name="frm" action="a.php" method="post" onsubmit="return check(this)">
<input type="text" name="age" id="ages">
<input type="submit" value="submit">
</form>

Upvotes: 2

Related Questions