Reputation: 683
i have a table where the first row are all text inputs sharing the same class name. i would like to set a validation so that user only enters float numbers. Does anyone know what i may be missing on the following code? $('input.' + classname) or $('.classname) doesn't fire any event when calling floatTextField() function
HTML code:
<td><div class="input-group"><input type="text" class="form-control myclass" value="2.8"></div> </td>
JavaScript code:
floatTextField('myclass');
function floatTextField(classname) {
$('input.' + classname).keypress(function (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (event.which == 0)//common keys
return true;
var value = $(this).val();
if (charCode == 45 && value.indexOf('-') != -1) {
return false;
}
else if (charCode == 46 && value.indexOf('.') != -1)
return false;
else if (charCode != 46 && charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$('input.' + classname).keyup(function (event) {
var value = $(this).val();
if (value <= 0 && value.indexOf('.') == -1 && value.indexOf('-') == -1) {
$(this).val('');
}
if (value.indexOf('-') > 0) {
value = value.replace('-', '');
$(this).val(value);
}
});
$('input.' + classname).change(function (event) {
var value = $(this).val();
if (value.indexOf('.') == 0) {
value = '0' + value;
$(this).val(value);
}
});
}
Upvotes: 0
Views: 2365
Reputation: 24276
You must use the $(document).ready()
method like this:
function floatTextField(classname) {
$('input.' + classname).keypress(function (event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (event.which == 0)//common keys
return true;
var value = $(this).val();
if (charCode == 45 && value.indexOf('-') != -1) {
return false;
}
else if (charCode == 46 && value.indexOf('.') != -1)
return false;
else if (charCode != 46 && charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$('input.' + classname).keyup(function (event) {
var value = $(this).val();
if (value <= 0 && value.indexOf('.') == -1 && value.indexOf('-') == -1) {
$(this).val('');
}
if (value.indexOf('-') > 0) {
value = value.replace('-', '');
$(this).val(value);
}
});
$('input.' + classname).change(function (event) {
var value = $(this).val();
if (value.indexOf('.') == 0) {
value = '0' + value;
$(this).val(value);
}
});
}
$(document).ready(function(){
floatTextField('myclass');
});
Upvotes: 1