Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created December 1, 2015 17:21
Show Gist options
  • Save Mottie/182adf51f05c932c53ff to your computer and use it in GitHub Desktop.
Save Mottie/182adf51f05c932c53ff to your computer and use it in GitHub Desktop.
jQuery nVal()
/* jQuery nVal() - A jQuery plugin that return numeric values from form elements
* this plugin uses jQuery .val() so it only uses the first element in the set of matched elements
* Examples: http://jsfiddle.net/Mottie/p2b89y5h/
<input value="1234.567">
$('input').val() // returns '1234.567' (string)
$('input').nVal() // returns 1234.567 (numeric)
$('input').nVal( 10 ) // returns 1234 (number; parseInt base 10 radix)
<select multiple>
<option value="10" selected>10</option>
<option value="20">20</option>
<option value="30" selected>30</option>
<option value="40">40</option>
<option value="50" selected>50</option>
<option value="60">60</option>
<option value="ten" selected>ten</option>
</select>
$('select').val() // returns [ '10', '30', '50', 'ten' ] (string values)
$('select').nVal() // returns [ 10, 30, 50, 'ten' ] (numeric values)
*/
;(function( $ ) {
// get element value (input/select/textarea)
var parseVal = function( val, base ) {
if ( isNaN( val ) ) {
return val;
}
if ( isNaN( base ) ) {
return parseFloat( val );
} else {
return parseInt( val, base || 10 );
}
};
jQuery.fn.nVal = function( base ) {
var val = this.val();
if ( Object.prototype.toString.call( val ) === '[object Array]' ) {
var indx = 0,
arry = [],
len = val.length;
for ( ; indx < len; indx++ ) {
arry[ indx ] = parseVal( val[ indx ] );
}
return arry;
}
return parseVal( val, base );
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment