I found that when jQuery get a value with 0 (for example 100)trail, it will omit it. So if I compare 5>100, the result is true. So how do I solve this?
here is the HTML code:
<form id="target">
<input type="text" id="max" value="100"/>
<input type="text" id="number" />
<input id="submit" type="submit" value="submit" />
</form>
And here is jquery:
$('#target').submit( function() {
var a = $("#number").val();
var b = $("#max").val();
if( a > b){
alert("exceed limit");
}
return false;
});
Here you can see demo: http://jsfiddle.net/yqMGG/91/
You need to compare the numeric values, not the string values. The output of the .val() function is a DOMString value according to DOM Level 2 which says:
interface HTMLInputElement : HTMLElement {
...
attribute DOMString value;
...
}
so your (5 > 100) test is really "5" > "100" which is true since strings are compared lexicographically.
The solution is to change
if( a > b){
to
if(+a > +b){
The + prefix operator coerces its argument to a number.
Use parseFloat(), otherwise the values are considered as strings.
$('#target').submit( function() {
var a = parseFloat($("#number").val());
var b = parseFloat($("#max").val());
if( a > b){
alert("exceed limit");
}
return false;
});
See Demo
You can multiply it by 1 to convert it from string to number, or use parseInt
var a = $("#number").val() * 1;
OR
var a = parseInt($("#number").val(), 10);
the second parameter of parseInt function is the radix.
Related
I have a simple if statment in a verify function that check at least 10 numbers are used in a field
function verfiyFields() {
var flag = true;
var number = $atj('#interested-number-form');
if(number.val().replace(/\s+/g, '').length < 10){
number.parent().prepend('<p class="form-error">Please enter phone number</p>');
fadeOut();
flag = false;
}
return flag;
}
How can I also check that only numbers are used.
You could use .match(/^\d+$/) to check if there are only digits.
var value = number.val().replace(/\s+/g, '');
if (value.length >= 10 && value.match(/^\d+$/)) {
// ..
}
You can also check if there are at least 10 digits using the regular expression /^\d{10,}$/ and avoid checking the length property:
var value = number.val().replace(/\s+/g, '')
if (value.match(/^\d{10,}$/)) {
// ..
}
As a side note, you can also use the pattern attribute:
<form>
<input type="text" pattern="^\d{10,}$" />
<input type="submit" />
</form>
function verfiyFields() {
var reg = /^\D*(?:\d\D*){10}$/;
var number = $atj('#interested-number-form');
var flag = reg.test(number.val())
if (!(flag)) {
number.parent().append('<p class="form-error">Please enter a valid 10 digit phone number</p>');
}
return flag;
}
Use RegExp.test(str) to check to make sure that the length of the field excluding all characters that are not digits is 10. RegExp.test returns a true or false value so this can be the flag you return.
RegExp.test(str) Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Demo:
http://jsfiddle.net/SeanWessell/1v6vnath/
I am trying to implement a validation check for an input text control which should allow only a positive integer value or a float with maximum 2 decimal places.
Here is the fiddler with the approaches I've tried: https://jsfiddle.net/99x50s2s/49/
HTML
Enter Price: <input type="text" id="price"/> (Example: 10, 10.50. Do not include $ symbol.)
<br/>
<br/>
<button type="button" id="check1">Check Method 1</button> (Fails when the value is 1.00)
<br/>
<br/>
<button type="button" id="check2">Check Method 2</button> (Passes when the value is 45f)
<br/>
<br/>
<button type="button" id="check3">Check Method 3</button> (Passes when the value is -10)
Code:
var price = $('#price');
$('#check1').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (String(num) === val && num >= 0)
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check2').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (((typeof num === 'number') && (num % 1 === 0)) || parseFloat(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check3').on('click', function(){
var val = $.trim(price.val());
if ($.isNumeric(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
Expectation:
The values that should be passed are positive numbers and float with maximum 2 decimals. (example 10, 10.50)
I looked at various answers in stackoverflow but non matched with my expectation. Any help is appreciated.
What you are really looking for is that the value matches a pattern, not what it's value is. For that, you are probably best off using a regular expression. Specifically, this should catch the value that you are looking for:
/^\d+(\.\d{1,2})?$/
That says:
starting at the beginning of the value (^)
match 1 or more digits (\d+)
followed by an option decimal point and 1 or two digits ((\.\d{1,2})?)
and no other characters before the end of the value ($)
That should enforce all of your rules, allowing you to perform a single check for validity, rather than multiple ones.
Edit: Here is an example of how to use it:
function checkNumber(sNum) {
var pattern = /^\d+(\.\d{1,2})?$/;
console.log(sNum + " is " + ((pattern.test(sNum)) ? "" : "not ") + "valid.");
}
checkNumber("1"); // 1 is valid.
checkNumber("-1"); // -1 is not valid.
checkNumber("1234"); // 1234 is valid.
checkNumber("1."); // 1. is not valid.
checkNumber("1.0"); // 1.0 is valid.
checkNumber("1.12"); // 1.12 is valid.
checkNumber("1.123"); // 1.123 is not valid.
I would imagine it would be:
var num = Number(val);
if (!isNaN(num)
&& num > 0
&& num == num.toFixed(2))
{
// Valid
}
I have this HTML:
<input type="number" id="num">
<input type="submit" onclick="test()">
and this script:
function test() {
var num = document.getElementById("num").value;
alert(num === 1);
so why do I get false when I enter 1 as my input?
If I try alert(num - 1 === 0); instead of alert(num === 1); I get true. Why does this happen?
The values of form controls are always strings (type="number" just asks the browser to enforce that the string contains a number). You can convert it to a number with +, parseInt, or parseFloat. You could also compare to "1" instead of 1.
If you subtract a number from a string, JavaScript will convert the string to a number before performing the subtraction, and then the result will evaluate as a number.
Consider changing it to a string.
function test() {
var num = document.getElementById("num").value;
alert(num === "1");
The === operator is much stricter and requires the compared values to be of both equal value and type. In this case you are comparing a string to a number.
Quentin's answer is correct, but just to add to it:
You can check if it is 1 using lazy equals (I.e. no type checking.) num == 1
Or, just compare against a string: num === "1"
in my current source code textbox value is 1.
when I try alert(isNaN(obj.text()) it returns false that is expected but after parseInt when I write alert(a); it returns NaN
minus.click(function () {
var a = 1; if (!isNaN(obj.text())) a = parseInt(obj.text());
if (a > 1) a -= 1; obj.text(a);
});
what is the problem?
Edit: this is the full code:
<input type="text" class="basket-txt" value="1" />
jQuery.fn.basket = function (options) {
var defaults = {
}
options = jQuery.extend(defaults, options);
this.each(function () {
var $this = $(this);
$this.height(32).css({ 'line-height': '32px', 'font-weight': 'bold', 'width':'40px', 'text-align':'center', });
var tbl = $('<table border="0" style="border-spacing:0px;float:left;">').appendTo($this.parent());
var tr1 = $('<tr>').appendTo(tbl);
var plus = $('<div class="basket-plus">');
$('<td>').append(plus).appendTo(tr1);
$('<td>').append($this).appendTo(tr1);
var minus = $('<div class="basket-minus">');
$('<td>').append(minus).appendTo(tr1);
var tr2 = $('<tr>').appendTo(tbl);
$('<td>').appendTo(tr2);
$('<td>').appendTo(tr2).append($('<div>').addClass('add-to-basket'));
$('<td>').appendTo(tr2);
$this.keypress(function (e) { if (e.which < 48 || e.which > 57) e.preventDefault(); });
minus.click(function () {
var a = 1; if (!isNaN($this.text())) a = parseInt($this.text());
if (a > 1) a -= 1; $this.text(a);
});
plus.click(function () {
var a = 1; if (!isNaN($this.text())) a = parseInt($this.text());
if (a < 1000000) a += 1; $this.text(a);
});
});
}
actually I knew I could correct the code and it would work my concern was to understand why isNaN returns false but parseInt returns NaN
The jQuery text() method will take all the descendent text nodes of an element and combine them into a single string.
An input element can't have descendant nodes of any kind. Its current value is exposed via the value property, which you can read with the val() method in jQuery.
You shouldn't use parseInt without a radix, especially with free form input. You might get octal or hex data instead of a decimal.
parseInt($this.val(), 10)
You get the value of an <input> with .val(), not .text().
The isNaN() function returns false for isNaN(""). Why? Because when "" (the empty string) is converted to a number, it's 0. Pass a non-number to isNaN() and the first thing it does is coerce the value into a number.
It's kind-of pointless to try isNaN() before parseInt() anyway, since parseInt() will tell you when it can't parse a nice-looking integer. Note however that parseInt() doesn't care if there's garbage at the end of the input.
If you want to convert a string to a number when it's a valid string representation of a number, and NaN when it isn't, you can use
var myNumber = +myString;
That'll accept numbers with fractional parts and exponents too, so you'd have to either truncate that to just an integer or check to see if it is one:
var myNumber = +myString;
if (isNaN(myNumber))
// not a valid number
else if (myNumber !== Math.floor(myNumber))
// not an integer
else
// yaay!
minus.click(function () {
// let's parse the integer first
var num = parseInt( obj.val(), 10 );
// then later, we can check if it's NaN
if ( !isNaN(num) && num > 1 ) {
num -= 1;
obj.val(num);
}
});
actually I knew I could correct the code and it would work my concern was
to understand why isNaN returns false but parseInt returns NaN
isNaN doesn't work the way it should. There is type coercion going on.
isNaN will convert the value to a number first. An empty string will be converted to a 0
Number("") === 0; // true
0 is obviously not NaN, so it returns false.
parseInt doesn't do type coercion, it parses the value differently.
Check this question and this other question for reference.
parseInt returns NaN when the first non-whitespace character cannot be converted to a number.
I want to pass in a value, obtained from the an html object, convert that value into an integer so I can run arithmetic on it before outputting it. As my code stands now, it just adds them up like a string. So a value of 5 + a modifier of 100 ends up equaling = 5100, not 105.
Here's my form code:
<form>
Add Amount: <select id="addTweets">
<option value=5>5</option>
<option value=10>10</option>
<option value=15>15</option>
</select>
</br>
<input type="button" value="Add It" onclick="addTweet()" />
</form>
Here's my script:
function addTweet()
{
var mod = 100;
var results = document.getElementById("addTweets").value;
results += mod;
document.getElementById("tweetsOutput").innerHTML = results;
}
The unary plus (+) coerces its operand into a number:
var results = +document.getElementById("addTweets").value;
...
typeof( results ); // number
Use parseInt:
var results = document.getElementById("addTweets").value;
var intResults = parseInt(results, 10) + mod;
You can use parseInt
var results = parseInt(document.getElementById("addTweets").value);
just add parseInt, then you could add it normally
var results = parseInt(document.getElementById("addTweets").value);
EDIT:
parseInt alternate, you can use "|0" use bitwise-or zero
var results = document.getElementById("addTweets").value|0;
Try:
var valResult = document.getElementById("addTweets").value; // get the value of the field
var results = parseInt(valResult) + mod; // convert the value to int to do calculation
document.getElementById("addTweets").value = results; // assign results to the field value
Generally, you can convert the string numerical values into integers by doing a mathematical operation on it:
x = "9"; //String numerical value
y = 10;//integer value
alert(x+y)// output 910;
x = x*1;
alert(x+y) // output 19
Checkout this demo