Javascript if function not working properly with getElemenById - javascript

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);
}
}

Related

Find the Least count number and then divide that number to specific remaing

I am trying to check each value of text box value as a localstorage id and get the specifiv value of that id and then check that value is equal to or greater then a specific value in my example the value local storage's Total_thrisholdvalue1 value
In this example the if condition works
Expecting some thing in else condition
My problem is while checking if the value is not grater then or equals to then on else condition by using the value of text box's on each condition it should find least number by using the above textbox value as the localstorage id as it is doing in if condition then divide the number for the remaining localstorage data value and check if the value match's the Total_thrisholdvalue1 if matches then alert that value else eliminate another most least untill the value is equal to or greater then Total_thrisholdvalue1
JS:
localStorage.setItem('Total_thrisholdvalue1','4');
localStorage.setItem('A9AH98','3');
localStorage.setItem('16B9BH','2'); localStorage.setItem('CC9GHF','4');
localStorage.setItem('A9D9G5','5');
$(".candidateid").each(function () {
var data = $(this).val();
var candidates_count = localStorage.getItem(data);
var Total_thrisholdvalue = localStorage.getItem('Total_thrisholdvalue1');
if (candidates_count >= Total_thrisholdvalue) {
alert(data );
} else {
}
});
Html:
<input type="text" value="A9AH98" class="candidateid">
<input type="text" value="16B9BH" class="candidateid">
<input type="text" value="CC9GHF" class="candidateid">
<input type="text" value="A9D9G5" class="candidateid">
The values retrieved from localStorage are strings, so the > operator won't work as you might expect. Parse them to ints first:
var candidatesCount = parseint(localStorage.getItem(data), 10);
var totalThresholdvalue = parseint(localStorage.getItem('Total_thrisholdvalue1'), 10);
if (candidatesCount > totalThresholdvalue) {
// etc.
}

Limit the input Field to take only numbers with range

I want to create a input field in html where can limit the users to enter a number only between the range -40 to 130.
The user can also enter decimal values
For example :
-40.2 (valid)
-40.23 (not Valid)
130(valid)
130.1 (not Valid)
So the input should be able to take in any number between the range and should only accept decimal place fixed to 1.
Any suggestions or help is highly appreciated
thanks in Advance
You can use an input of type number with the attributes min max and step like this :
<form action="">
<input type="number" min="-40" max="130" step="0.1" id="input"/>
<button type="submit">Ok</button>
</form>
I provide a JSFiddle here. When you try to submit the form, the html5 validation displays a message if the number is out of the bounds or with more than one decimals.
JSFiddle
as Xartok told You can use an input of type number with the attributes min max and step but if the user is keying in the input its a bit hard from my experience. what i did was like this.
onkeypress is used to allow users to only key in integers with decimal only.
ng-blur is used to trigger changeDecimal function to do the validation/rounding up to fixed decimal places
<form>
<input type="text" id="input" onkeypress="return event.charCode >= 45 && event.charCode <= 57 && event.charCode!=47" ng-model="input1"ng-blur="changeDecimal()" />
<button type="submit">Ok</button>
</form>
and from the controller side what i did was this :
1st i parse the input to float and fix it to 1 decimal place.
then i made a condition to check the range if it is within the range, the input is replaced with the new value else an alert is returned.
in the else section i did a small check if the input is blank or not a number then replace with a default value (to avoid a loop of alert if the input is left blank)
app.controller('MainCtrl', function($scope) {
$scope.changeDecimal = function (){
temp = parseFloat($scope.input1).toFixed(1);
if (temp > -40 && temp < 130 && !isNaN(temp)){
$scope.input1= temp;
}else{
alert("value out of range ");
if (isNaN (temp) || temp == null || !angular.isDefined(temp)){
$scope.input1=0;
}
}
}
});
If you plan to use the input type as number what you can do is set a condition for you submit button (ng-disable). the button is disabled until the condition is met.
here is the sample from Plunker

jQuery: how to set fixed decimals for input field value

I have a basic input field in which an amount is to be filled in.
The field is formatted as text as it also has to work with older browser versions.
Is there a way I can use jQuery and/or Regex to set fixed decimals (2) to any number in this field ?
I tried the following but this doesnt change anything:
<input type="text" class="span6" id="amount" maxlength="12" name="amount" />
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^\d+$/) ) {
$('#amount').val( amount.toFixed(2) );
}
});
What I am looking for is a way to add two decimals to the input value if there are none and the input is a number.
Examples:
1000 should become 1000.00
1000.99 should stay 1000.99 as there are already two decimals.
Many thanks for any help with this, Tim.
I have created a fiddle, please check Fiddle
before using toFixed convert the amount to integer parseInt(amount).
Edit
Code
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^$/) )){
$('#amount').val( parseInt(amount).toFixed(2));
}
});

Why is my condition showing false results?

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).

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.

Categories