0

I am trying to validate a input field. The input field should take only numbers, if not it will alert "input must be a number". And if the field is empty it will do nothing. But when I left the field empty it will aslo alert me. How can I fix this. Here is my code

<div class="form-group">
<label class="col-lg-2 control-label">Gross Salary</label>
<div class="col-lg-8">
<input class="form-control" placeholder="Gross Salary" type="text"      name="gross_salary"id="tax4">
</div>
</div>

and javascript code

<script type="text/javascript">
    var validate_int_taxid = function() {
    var tax = document.getElementById("tax4");
    var tax_id = parseFloat(tax.value);
    if (isNaN(tax_id)) {
        alert("Gross Salary  must be a Number");
        return false;
    }
    return true;
}
</script>

Thank You

4
  • 3
    Why did you tag CSS and PHP for this question? Commented Apr 8, 2014 at 7:19
  • I'm not sure about this but probably isNaN() probably checks for empty and null values aswell Commented Apr 8, 2014 at 7:20
  • Thanks guys. I solve it by myself <script type="text/javascript"> var validate_int_taxid = function() { var tax = document.getElementById("tax4"); if(tax.value.length == 0) return true; var tax_id = parseFloat(tax.value); if (isNaN(tax_id)) { alert("Gross Salary must be a Number"); return false; } return true; } </script> Commented Apr 8, 2014 at 7:55
  • I am reallly sorry Viswalinga Surya S Commented Apr 8, 2014 at 7:55

3 Answers 3

2

make it like

var tax = document.getElementById("tax4");

if(tax.value!="") {
    var tax_id = parseFloat(tax.value);
    if (isNaN(tax_id)) {
       alert("Gross Salary  must be a Number");
       return false;
    }
    return true;
} else {

    return false;
    //do nothing

}

Here is a fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

Here you go:

<script type="text/javascript">
var validate_int_taxid = function() {
    if (tax.value !="") {
        var tax_id = parseFloat(tax.value);
        if (isNaN(tax_id)) {
            alert("Gross Salary  must be a Number");
            return false;
        }
        return true;
    } 
    return false;
}
</script>

Comments

0

Try with this.

<script type="text/javascript">
    var validate_int_taxid = function() {
    var tax = document.getElementById("tax4");
    if(tax.value!="" )
    {
    var tax_id = parseFloat(tax.value);

    if (isNaN(tax_id)) {
        alert("Gross Salary  must be a Number");
        return false;
    }
    }
}
</script>

1 Comment

@Girish..that was the right way..It will return true if it is not a number..Then why u downvote for it. I am not getting !!..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.