Reputation: 103
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
Upvotes: 0
Views: 95
Reputation: 8369
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>
Upvotes: 0
Reputation: 1798
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>
Upvotes: 0
Reputation: 27835
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.
Upvotes: 2