jQuery change text box value not working - javascript

I'm trying to display total price in sum label by multiplying qtyTxt value (user entered) with price. But it doesn't work, the if statement is never reached.
<input type="text" name="qtyTxt" value="1" size="2" style="width: 25px"/>
<label id="price">${adClicked.price}</label>
<label id="sum">${adClicked.price}</label>
<input type="hidden" name="id" value="${adClicked.id}"/>
<script>
$(".qtyTxt").bind('change', function () {
var sum=$(("#price").val())* ($(this).val());
$("#sum").val('Rs.'+sum);
});
</script>
There are no errors in the console and $("#sum").val('Rs.'+sum); works fine.

1) Use parseInt() or parseFloat() The parseInt() function parses a string and returns an integer.
2) Another mistake Don't use val() for label instead of use text() for label
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
code be
$(".qtyTxt").bind('change', function () {
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
$("#sum").text('Rs.'+sum);
});

Two issue:
1) You have error in your code, $(("#price").val()) should be $("#price").text() or $("#price").html()
2) You need to parse the values before doing mathematical calculation:
var sum=parseInt($("#price").text(),10)*parseInt($(this).val(),10) ;

Related

Not showing result with decimal discount value

I have a discount jquery calculator plugin.It is working. But percentage is not working with decimal values like Eg: 5.45%, 10.50% , 15.70%, 20.75% etc.. I created a Codepen project for it. Please check this Codepen link https://codepen.io/coderco/pen/gOeReMQ . Here is my codes. Please help me..
HTML
<input type="text" id="Amount" value="">
<input type="text" value="10.45" id="Discount">
<input type="text" id="Result">
Script
$(document).on("change keyup blur", "#Discount", function() {
var main = $('#Amount').val();
var disc = $('#Discount').val();
var dec = (disc / 100).toFixed(2); //its convert 10 into 0.10
var mult = main * dec; // gives the value for subtract from main value
var discont = main - mult;
$('#Result').val(discont);
});
It's because of toFixed(2). When you divide the value by 100 then there are 4 decimal places.
For example:
Amount = 100, Discount = 10.45
dec = (10.45/100) = 0.1045 (Calling toFixed(2) changes it to 0.10 that means 10 instead of 10.45).
In my suggestion add toFixed(2) to the final answer (discount), Instead of while calculating.

javascript distribution of inputs

I am trying to do 2 things:
Balance out 3 inputs into 100
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function () {
$input2 .val(100 - this.value);
$input3 .val(100 - this.value - $input2.value)
});
$input2 is displayed well yet doesn't output into $input3 (NaN).
I also tried to create a callback for input3 and that didn't work out well either.
How to block the input from showing numbers out of the range of 0-100.
Here's a JSF
Try to get rid of jQuery because you are confusing both the DOM API and jQuery API. The DOM is what you should learn, not jQuery.
let $input1 = document.querySelector('#input1');
let $input2 = document.querySelector('#input2');
let $input3 = document.querySelector('#input3');
$input1.addEventListener('input', function () {
$input2.value = (100 - this.value)/2;
$input3.value = 100 - this.value - $input2.value;
});
<form>
<input id='input1'/><br/>
<input id='input2'/><br/>
<input id='input3'/>
</form>
$input2 is a jQuery wrapped element. You cannot call value on it directly. You need to get the value using val() instead. Since value will return undefined, the final output is NaN.
Change this:
$input3.val(100 - this.value - $input2.value)
to this:
$input3.val(100 - this.value - $input2.val())
Alternatively, you can get the native element out of the jQuery wrapper and call value on it. The following should work seamlessly as well:
$input3.val(100 - this.value - $input2[0].value)
For #2, you may want to look into input[type=number] and restrict the range using min and max attributes.
As in other answer by #31piy you need to use $input2.val() or $input2[0].value. And balancing of values in field input2 and input3 can be done as below.
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function() {
$input2.val(parseInt((100 - this.value) / 2));
$input3.val(100 - this.value - $input2.val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="input1" type=number min="0" max="100">
<input id="input2" type=number min="0" max="100">
<input id="input3" type=number min="0" max="100">

Input type number adding 10 to value [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 4 years ago.
I just found a weird behaviour in the simplest code ever and I'm wondering why this is happening.
I have 3 inputs (a, b, c) of type number and whenever they change I store the value with jQuery in a global variable (one variable for each input). Then I call a function that calculates the average of the 3 variables (a + b) / c. When I console.log the variables and the total, it is returning ((a + 10) + b) /c. Somehow it is adding 10 only to the first variable and I have no idea why.
number_a = 0;
number_b = 0;
number_c = 0;
$('#a').bind('input propertychange', function() {
number_a = $(this).val();
calculate();
});
$('#b').bind('input propertychange', function() {
number_b = $(this).val();
calculate();
});
$('#c').bind('input propertychange', function() {
number_c = $(this).val();
calculate();
});
function calculate() {
var total = 0;
if (number_c) {
total = (number_a + number_b) / number_c;
} else {
total = (number_a + number_b) / 1;
}
console.log(number_a, number_b, number_c);
console.log(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" placeholder="a" />
<input type="number" id="b" placeholder="b" />
<input type="number" id="c" placeholder="c" />
I know I can solve this using parseInt() with the value i get from the inputs as they are strings but It's weird It only happens with the a input and exactly 10 everytime.
Do you guys know why this is happening?
Use parseInt() as you said otherwise the input values will be treated as strings.
$('#a').bind('input propertychange', function() {
number_a = parseInt($(this).val());
// call the calculation function
calculate();
});

Input value still a string after parsing to float

I don't know where am I failing. I am trying a simple thing: retrieve an input, parse it to float and do a calculation with that value (introduced by the user), but yet, it returns NaN.
Here it is the input (I make a string replace of commas to dots in my code, but right now I am just trying the simplest way in the Firebug console):
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">
This is what I am trying:
var percent = parseFloat($('#percent_31').val()).toFixed(2);
console.log(percent);
console.log(jQuery.type(percent));
/*This returns -3.33 and string type*/
console.log((100 + percent)/100);
/*This, as expected, returns NaN*/
This, on the other hand, works.
percent = -3.33;
console.log(percent);
console.log(jQuery.type(percent));
/*This returns -3.33 and number type*/
console.log((100 + percent)/100);
/*This returns what I need: 0.9667*/
If you want to round up to two decimals:
> percent = "-3.33678";
'-3.33678'
> typeof(percent);
'string'
> percent = Number(parseFloat(percent).toFixed(2));
-3.34
> typeof(percent);
'number'
If you want to truncate the decimals and not round them:
> percent = "-3.33678";
'-3.33678'
> typeof(percent);
'string'
> percent = Number(percent.slice(0, (percent.indexOf(".")) + 3));
-3.33
> typeof(percent);
'number'
You can use 'Number()'
var values = $('#percent_31').val();
var percent = Number(parseFloat(values).toFixed(2));
console.log(percent);
//console.log(jQuery.type(percent));
/*This returns -3.33 and string type*/
console.log((100 + percent)/100);
/*This, as expected, returns NaN*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">
create a variable and assign value to that variable.
var myvalue = $('#percent_31').val();
var percent = parseFloat(myvalue).toFixed(2);
console.log(percent);
The jQuery method val() is returning an string, so you can use Number() to work with the numerical value:
var val = $('#percent_31').val(),
percent = Number(parseFloat(val).toFixed(2)),
result = (100 + percent) / 100;
console.log('percent:', percent);
console.log('type:', $.type(percent));
console.log('result:', result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="percent_31" class="form-control input-sm text-right" type="text" name="percent[31]" value="-3.3333">

always want to keep first digit of my textfield as 0

hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]

Categories

Resources