Why is my condition showing false results? - javascript

I have this condition using JavaScript, I have 2 text boxes where I'll compare the input ( inputs are numbers). The condition is when textbox 2 is less than textbox 1 it will have an alert message that says textbox2 must be greater than textbox2. So when the input is like this
textbox2 > textbox1
15 > 1 = alert pops out
15 > 2 = not ok
15 > 3 = not ok
15 > 4 = not ok
15 > 5 = not ok
15 > 6 = not ok
15 > 7 = not ok
15 > 8 = not ok
15 > 9 = not ok
15 > 10 = ok
onwards is ok.
Why is it that when it compares 2 to 9 it doesn't alert anything?
Here is my condition:
if(textbox2.value < textbox2.value)
{
document.getElementById("lblStatus1").innerHTML = 'Pay1 must be greater than To1';
}

The problem here is that you are comparing strings, which is different than comparing numerical values.
"15" is < "2" Because it's evaluated alphabetically character by character . The leading '1' in '15' causes '15' to be < '2'

You are comparing strings. Which will not work as you intended to.
Use parseInt():
if(parseInt(textbox2.value) < parseInt(textbox2.value))
{
document.getElementById("lblStatus1").innerHTML = 'Pay1 must be greater than To1';
}

Are you parsing your input values? If not, you're doing a comparison against strings which would result in an issue. Something like this:
parseInt(inputVal1, 10) > parseInt(inputVal2, 10)

If you copy and pasted your code...
You're comparing the same values textbox2.value and textbox2.value.

You are having an issue related to validating strings. Try to parse the values as numbers:
JsFiddle
HTML
Value 1<input type="text" id="text1" /><br />
Value 2<input type="text" id="text2" /><br /><br />
<input type="button" value="Validate" onclick="doValidate();" />
Js
function doValidate() {
var value1 = new Number(document.getElementById("text1").value);
var value2 = new Number(document.getElementById("text2").value);
if (value2 < value1)
alert("Value 2 must be higher than Value 1!");
}
Notice the usage of new Number() in JavaScript. This effectivelly turns the string into a number (if it is a valid number).

Related

Javascript if function not working properly with getElemenById

okey so I got this, kinda look at it like u have a website were u can redeem points, now when I click redeem I dont want that the number given is lesser than 4 points and that the number given is greater than your balance of points.
Now when I click the button when the input is 2, I will get 2 alerts (alerts are for testing)
But, as soon as I click the button when I put an number lesser than my balance, I also get 2 alerts, saying number = (for example) 7 and balancehidden = 100. So I dont understand why I get those alerts. because its lesser than the balance and greater than 4.
also this is the field the balance get stored when refreshBalance() get called:
<input type=hidden id="balancehidden" name="balancehide"
value=""/>
Javascript :
<input type="text" id="number"><br>
<button type="button" class="btn btn-success" id="redeem">Redeem</button>
<body onload="refreshBalance()">
<script type="text/javascript">
document.getElementById('redeem').onclick = function() {
if(document.getElementById('number').value < 4 || document.getElementById('number').value > document.getElementById("balancehidden").value)
{
alert(document.getElementById("number").value);
alert(document.getElementById("balancehidden").value);
}
}
</script>
You're trying to see whether one string is greater than another string, but what you really want to do is compare numbers.
Counterintuitively, "4" > "100" === true while 4 > 100 === false.
Convert your values to numbers:
if(parseInt(document.getElementById('number').value) < 4 || parseInt(document.getElementById('number').value) > parseInt(document.getElementById("balancehidden").value))
Use parseFloat instead of parseInt if you expect decimals, and be aware of the radix parameter.
The problem is that you are trying to compare string values instead of integers.
Please check this jsfiddle with working code: https://jsfiddle.net/2kbcuhg9/
document.getElementById('redeem').onclick = function() {
var number = parseInt(document.getElementById('number').value);
var balance = parseInt(document.getElementById('balancehidden').value);
if(number < 4 || number > balance) {
alert(document.getElementById("number").value);
alert(document.getElementById("balancehidden").value);
}
}

Convert int with starting zeros to string to check length

I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.

JQuery: Change value when value of other input field is changed with a range of numbers

I was wondering if someone can help me develop this in Jquery (mobile):
I want to make two text fields, in the first one you have to enter a number and in the other one I want to see a result. I mean something like this:
example 1:
textfield 1: 220 till 285 < input
textfield 2: 1 < result
example 2:
textfield 1: 286 till 350 < input
textfield 2: 2 < result
example 3:
textfield 1: 351 till 415 < input
textfield 2: 3 < result
This must happen automatically and not with pressing a button, etc., like this method
UpdATE!
What i mean is more a range like this: input: for example the numberrange 220 till 285 will result in 1. 286 till 350 in 2. 351 till 415 in 3. So all the numbers between for example 351 - 415 must has 3 as output
Simply use the keyUp event provided by jquery:
html
<input type="text" id="input" />
<input type="text" id="output" />
js
$('#input').keyup(function() {
$('#output').val($('#input').val().substring(0,1));
});
http://jsfiddle.net/uGLpt/
EDIT
You can check the input with simple if-conditions:
$('#input').keyup(function () {
var value = $('#input').val();
if(value >= 220 && value <= 285)
$('#output').val(1);
else if(value >= 286 && value <= 350)
$('#output').val(2);
else if(value >= 351 && value <= 415)
$('#output').val(3);
else
$('#output').val("");
});
http://jsfiddle.net/uGLpt/4/
Is this what you want fiddle
$(document).ready(function(){
$("#txt1").keyup(function(){
$("#txt2").val($("#txt1").val()/50);
});
});
<input type="text" id="txt1" />
<input type="text" id="txt2" />

add + 1 to <input> value for each click event. increment stops at number 3 Javascript/jQuery

by default my input value is 1, i want to add +1 each time i click my button. it stops adding when when it reaches 20.
i cant figure out why my code stops at number 3 and just repeats 3.
this is my HTML
<input type="hidden" id="total" value="20" /> //total num
<input type="hidden" id="cur_num" value="1" /> //current num
<button type="button" id="add" >Add</button>
this is javascript and demo here http://jsfiddle.net/zXpen/
$(document).ready(function() {
$(document).on("click", "#add", function() {
cur = $('#cur_num').val();
total = $('#total').val();
console.log(cur);
if (cur <= total) {
cur = parseInt(cur)+parseInt(1);
$('#cur_num').val(cur);
}
});
});
.val() returns a string, so cur <= total is comparing two strings lexicographically, i.e. characters at each position are compared against each other. And "2" in "20" is smaller than "3" in "3".
You have to convert the values to numbers before you compare them, not after that, e.g. by using the unary plus operator. Also don't forget to declare your variables with var:
var cur = +$('#cur_num').val();
var total = +$('#total').val();
You need to convert your values to integers:
cur = parseInt($('#cur_num').val());
total = parseInt($('#total').val());
At the moment your code is comparing "2" <= "20", then "3" <= "20" (as strings). Therefore the if condition is not met and the code within it is not run.
Also, you don't need parseInt(1). cur = parseInt(cur)+1; is fine.

Restrict numbers and limit them to two

How to restrict my text field to numbers only and limit them in two with a single function.
Since no one has suggested a regular expression, I will. :-)
var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
// number is one or two digits with optional leading minus
} else {
// it's not
}
For limiting them to enter only 2 char use maxlength attribute of input. To check enter string is number or not user isNaN(str) function.
<script type="text/javascript">
function ValidateField(FieldName){
// Get fields value
var FieldVal = document.GetElementById(FieldName).value;
// Check it's a number, and then check it's range is correct
// Alternatively you could do FieldVal.length
if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
alert("Valid!");
else
alert("Invalid");
}
</script>
<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>
I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.
In HTML5 you can just use: <input type="number" />
If you are using jquery:
$('#myTextAreaID').keydown(function(event) {
if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105

Categories