angularjs Nan Is Appearing if textbox is empty - javascript

I am creating a web app in which I am calculating a $scope variable with a textbox, but if a user put textbox empty or if a user don't enter anything on textbox the result is coming NaN here is my code
<input type="text" ng-model="amount1" ng-blur="amountchange(amount1)" />
{{total}}
And in my controller I have
$scope.amountchange = function () {
$scope.total = parseInt($scope.amount1) + parseInt($scope.total);
}
I want to get rid off the NaN which is apearing if the textbox is empty
Here is a fiddle that I created for better understanding
CLICK HERE

Use
$scope.constant = 200; //Define other variable to persist constants
$scope.total = $scope.constant; //Initialize total
$scope.amountchange = function() {
var amount1 = parseInt($scope.amount1, 10) || 0; //parse amount if its invalid set it to zero
$scope.total = $scope.constant + amount1; //update total
}
DEMO

Related

inserting random number into hidden field on submit

Trying to insert a random number into a hidden field in a form using javascript. Not passing any value since SQL error of - doesn't have a default value
var randomNum = '';
randomNum += Math.round(Math.random()*5);
var elem = document.getElementById("randSS").value = randomNum;
<input name="randSS" type="text" id="randSS"/>
Didn't have protected fillable added!

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

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Strange jquery bug in simple code

I have a simple html code with form:
<span class="price"></span>
Enter amount:
<input type="text" class="form-control amount" name="amount" value="500">
<!--Next input fields are hidden by Bootstrap class "hide"-->
<input type="text" name="minimal-amount" class="hide minimal-amount" value="500">
<input type="text" name="oneprice" class="hide oneprice" value="0.20">
<script>
$(".amount").on("change", function(){
var am = $(".amount").val();
var min = $(".minimal-amount").val()
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
</script>
Idea of this code is very simple. When user put in amount field digits, my script should check, if that, what user put is smaller than minimum available value in minimal-amount field, script changes value of amount field to default minimal-amount.
But the problem is, that id I just add 0 in amount field (and it's value become 5000) everything is ok, but when I changes value of amount field to 1000, script changes value of amount field to default, as if it smaller them minimul-amount.
What I do wrong, and how can I fix this problem?
P.S. Example of this code you can find here - http://friendfi.me/tests/amount.php
You should parse the value before use. Because .val() will return only string type.
$(".amount").on("change", function(){
var am = parseFloat($(".amount").val());
var min = parseFloat($(".minimal-amount").val());
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
There are a lot of gotchas in that code. Here is a working JSBin: http://jsbin.com/qilob/2/edit?html,js,output
Highlights
You need the DOM to be initialized before you can work with it.
Wrapping this in a function passed to jQuery will make it wait till
the page finishes loading before manipulating it.
$(function() { ... });
Use cached values since the elements are not going to change much.
This saves the need to parse the selectors multiple times. It also saves
on typing and readability.
var $amount = $("#amount");
var $minimalAmount = $("#minimal-amount");
var $onePrice = $("#oneprice");
var $finalPrice = $("#price");
When parsing a string to an Int you need to use parseInt
var amount = parseInt($amount.val(), 10);
Conversely when parsing a string to a Float you need to use parseFloat
var price = parseFloat($onePrice.val());
JavaScript can not handle float based arithmetic well.
rounding errors are bad especially when dealing with money we need
to move the decimal place to prevent rounding errors in the more significant
parts of the price value.
var total = (amount * (price * 100)) / 100;
See it in action in the JSBin.

issue in disabling submit button using jquery

i am iterating a list , and displaying its values in textboxes.
there is two textboxes with name checkquantity & quantity whose values i am iterating from a list.
Now users have to enter the quantity values, if they enter the quantity values more then the allocated quantity. Then i have to disable the submit button.
This is my problem:
From my below code , submit button is diasabling for first time only. i.e. if i enter invalid values for first time then my code is working fine but if again i enter valid values in another text-box then my button is enabling. But it should not enable since in first textbox invalid values are entered.
Note: Users can only enter values in textbox name quantity and this textbox will be validated from the textbox checkquantity.
Please check my below code and suggest me a solution for this.
$('input[name="quantity"]').keyup(function() {
var $tr = $(this).closest("tr");
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q > cq) {
$('#submtbtnId').attr('disabled', 'disabled');
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});
----------------------------------- in
while loop my list is iterating
{
<tr>
<td width = "10%">
<input type = "text" name = "quantity"values = "" id = "quantity" / >
<input type = "text" name = "checkquantity" disable = "disable"
values = "random values coming from my list
eg. 5 or 9 ..." / > < /td>
</tr >
}
-------------------------
< input type = "submit" id = "submtbtnId" / >​
If that's the case every time in the keyup event check all the textboxes by iterating over them..
UPDATE
Looks like the issue is with the attribute named values .
If you are trying to access the value using .val() then it is supposed to be value.
Added the return false; condition to make sure it breaks out of the loop when the condition fails.
Secondly there was one more issue.. Lets say the input is empty .. So when you convert that to a number then it is 0 and the comparison always fails..
So i have added a check condition if the field is not empty , only then convert to the number
$('input[name="quantity"]').on('keyup', function() {
var check = false;
$('tbody tr').each(function() {
var $tr = $(this);
var q = $tr.find('input[name^="quantity"]').val();
if(q != ''){
q = +q;
}
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q !== '' && q > cq) {
check = true;
return false;
}
});
if (check) {
$('#submtbtnId').prop('disabled', true);
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});​
Check Fiddle

Categories