I am doing some calculations based on values from two text inputs. Values could be floats or ints. The calculations are triggered on the keyup
event.
So at the moment I have to evaluate the val to determine if it is a float or int and then use parseInt
or parseFloat
as appropriate.
This seems a bit hacky or overkill. Is there a better way to do this?
Here's a fiddle to demonstrate: https://jsfiddle.net/2hw0tnhb/
HTML:
<label id="x-label" for="x">Float</label>
<br/>
<input type="text" name="x" id="x" value="29.7" class="axis"/>
<br/>
<br/>
<label id="y-label" for="y">Int</label>
<br/>
<input type="text" name="y" id="y" value="21" class="axis"/>
JS:
var $x = $('#x');
var $y = $('#y');
var $axis = $('.axis');
var x_label = $('#x-label');
var y_label = $('#y-label');
$axis.keyup(function(){
var $this = $(this);
var val = $this.val();
var axis = 'x';
if($this.attr('id') === 'y') axis = 'y';
//check if int or float:
if(parseFloat(val) > Math.floor(parseFloat(val))){
//it is a float - use parseFloat()
if( axis === 'x' ){
x_label.text('Float');
}else{
y_label.text('Float');
}
}
else{
//it is an int - use parseInt()
if( axis === 'x' ){
x_label.text('Int');
}else{
y_label.text('Int');
}
}
});