jQuery: Value of an input doesn't save in a variable - javascript

I can't save what I have in my input in a variable. It saves as a blank space or if it's an integer: 0
This is my code:
function attachKeyupEventDescuento(inputElement, i) {
var cantidad = $('#txt_compras_cantidad' + i).val()
var costo = $('#txt_compras_costoUni' + i).val()
total = (cantidad * costo)
$(inputElement).keyup(function() {
console.log(total)
if (inputElement.val() !== '') {
var descuento = inputElement.val()
var descuentoTotal = ($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val()) - ($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val() * (descuento / 100))
$('#spn_compras_total' + i).text(descuentoTotal.toFixed(2))
sumarprecioFinal()
} else {
$('#spn_compras_total' + i).text(($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val()).toFixed(2))
}
})
}
Let me explain the code:
var cantidad = $('#txt_compras_cantidad' + i).val()
var costo = $('#txt_compras_costoUni' + i).val()
If I save them in those variables, I get a blank space, but if I use them without saving them in a variable, they work perfectly. Why does it happen?
This function is called from a button that created a new row in my table. The inputelement is the current input on which to attach the keyup event.

Please find the updated code
function attachKeyupEventDescuento(inputElement, i) {
var cantidad = parseInt($('#txt_compras_cantidad' + i).val());
var costo = parseInt($('#txt_compras_costoUni' + i).val());
var total = (cantidad * costo)
$(inputElement).keyup(function() {
console.log(total)
if ($(inputElement).val() !== '') {
var descuento = parseInt($(inputElement).val());
var descuentoTotal = (cantidad * costo) - (cantidad * costo * (descuento / 100));
$('#spn_compras_total' + i).text(descuentoTotal.toFixed(2))
sumarprecioFinal()
} else {
$('#spn_compras_total' + i).text((cantidad * costo).toFixed(2))
}
})
}
When you get value from an input, it's always a string. Try parsing the value of an input.

Related

how to get value from select without refresh?

I made a CGPA-SGPA calculator and I cannot get the value with refresh.
When I refresh and check the value it get feed
but not getting value without refresh.
var credit_1001 = document.querySelector('#credit_1001')
var grade_1001 = document.querySelector('#grade_1001')
var credit_1002 = document.querySelector('#credit_1002')
var grade_1002 = document.querySelector('#grade_1002')
var credit_1003 = document.querySelector('#credit_1003')
var grade_1003 = document.querySelector('#grade_1003')
var credit_1004 = document.querySelector('#credit_1004')
var grade_1004 = document.querySelector('#grade_1004')
var credit_1008 = document.querySelector('#credit_1008')
var grade_1008 = document.querySelector('#grade_1008')
var credit_1009 = document.querySelector('#credit_1009')
var grade_1009 = document.querySelector('#grade_1009')
//btn and result S1
var btn_check = document.querySelector('#check_s1')
var result_s1 = document.querySelector('#result_s1')
//btn click S1
var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
btn_check.addEventListener('click', () => {
result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
console.log("S1 Total Credit = " + total_s1_credit)
console.log("S1 Got Marks = " + got_s1_marks)
console.log("S1 SGPA = " + result_s1.innerText)
})
You need to get the values for your calculation inside of the click handler, right now you get them before the click, and then use (the old values) when the click happens
btn_check.addEventListener('click', () => {
//btn click S1
var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
console.log("S1 Total Credit = " + total_s1_credit)
console.log("S1 Got Marks = " + got_s1_marks)
console.log("S1 SGPA = " + result_s1.innerText)
})

Random math quiz on JavaScript

I am trying to make a random math quiz and I want to get new random numbers
after every click on the button.
I success to get new random numbers on every click but I still get the result of the first random numbers I got on the loading on the page
Another thing I need help to increase the score size-font every time the user enters the correct answer.
I tried to do it with 2.0em but it increases only once.
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<h1 style="font-size: 400%">Random Math Quiz</h1>
<div id="question"></div>
<input type="text" name="answer" id="answer" style="width: 250px; height: 40px; font-size: 32px;">
<br><br>
<button onclick="quiz()">Enter</button>
<br><br>
Score: <div id="score">0</div>
</center>
<script src="script.js"></script>
</body>
</html>
JavaScript
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
function quiz() {
{
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score ;
document.getElementById("question").style.fontSize = "2.0em";
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
}
}
The reason your numbers do not change, is because every time you call that quiz function, you did not change the original int1 and int2. The whole javascript is only loaded once and and two numbers will only be set at a random number, once. Unless you fire a function to change the variables.
try this:
var score=0;
var int1 = Math.floor(Math.random() * 10) + 1
var int2 = Math.floor(Math.random() * 10) + 1
var answer = int1 + int2;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
function quiz() {
var user_answer = document.getElementById('answer').value;
if (user_answer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
// you need to reset the int1, int2, and answer by generating new numbers
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
answer = int1 + int2
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
}
Since int1 and int2 are outside of the function they going to have the same value.
You need to generate a new random number each time you call the function quiz().
same with the font size - you changed it only once from default to 2em when you need to increase the value every time you call quiz().
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
var fontSize = 1;
function quiz() {
{
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score ;
document.getElementById("question").style.fontSize = fontSize + 'em';
fontSize++;
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
answer = int1 + int2;
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score ;
}
}
}
What about this approach? You call a function in order to reset the random values after each guess. And you store your fontSize in a variable, which you increase by 2 each time the user guesses right.
// intitial setup
var int1 = Math.floor(Math.random() * 10) + 1;
var int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var answer = int1 + int2;
var score=0;
var fontSize = 2;
function quiz() {
var uanswer = document.getElementById('answer').value;
if (uanswer == answer) {
alert("Correct");
score=(score)+1;
document.getElementById('score').innerHTML =score;
document.getElementById("question").style.fontSize = fontSize + ".0em";
// increase fontSize by 2 for the next correct answer
fontSize += 2;
} else {
alert("OOPS Try Again!")
score= (score)-5;
document.getElementById('score').innerHTML =score;
}
// set new values
resetValues();
}
resetValues = () => {
int1 = Math.floor(Math.random() * 10) + 1;
int2 = Math.floor(Math.random() * 10) + 1;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
answer = int1 + int2;
score=0;
}

how to keep ionic from refreshing page when using firebase

i making a counter when everytime a users click a button it substracts 1 from the counter updates the node in firebase then return this change via another method with .valuechanges.subscribe
but everytime this happens it refreshes the whole page deleting all user inputs.
constructor(private dd: PlayerInfoProvider, private strge: Storage, private ss: Slot2machineProvider, private slotProvider: SlotProvider) {
this.slotProvider.getTries(this.dd.getCurrentUser()).valueChanges().subscribe(snapshot => this.gettries(snapshot));
}
gettries(snapshot) {
// this.playerObject = snapshot;
this.tries = snapshot;
}
runSlots() {
if (this.tries <= 0) {
alert("you cannot play anymore sorry!! but if you want you can purchase some more luck");
} else {
this.slotOne = Math.floor(Math.random() * 52) + 1;
this.slotTwo = Math.floor(Math.random() * 52) + 1;
this.slotThree = Math.floor(Math.random() * 52) + 1;
this.slotFour = Math.floor(Math.random() * 52) + 1;
this.slotFive = Math.floor(Math.random() * 52) + 1;
// this.sloty1 = '<p > "' + this.slotOne + '"</p>';
// this.sloty2 = '<p > "' + this.slotTwo + '"</p>';
// this.sloty3 = '<p > "' + this.slotThree + '"</p>';
// this.sloty4 = '<p > "' + this.slotFour + '"</p>';
// this.sloty5 = '<p > "' + this.slotFive + '"</p>';
if (this.slotOne !== this.slotTwo || this.slotTwo !== this.slotThree) {
this.loggerr = "<h2>sorry try again.. </h2>";
this.playerObject.tries = this.tries - 1;
//alert("you only have " + this.playerObject.tries + " chances left ");
// this.ss.substractTries(this.dd.getCurrentUser(), this.playerObject);
} else {
this.loggerr = "<p>jackpot!!!</p>";
}
}
}

Transform HH MM SS in seconds

I need to transform 3 form inputs (HH, MM, SS) in seconds with javascript.
I have this code but it has only with 1 form input in seconds : https://jsfiddle.net/94150148/hhomeLc3/
To do this I need a new javascript function.
window.onload = function () {generate()};
function generate() {
var width = 'width=\"' + document.getElementById('width').value + '\" ';
var height = 'height=\"' + document.getElementById('height').value + '\" ';
var ytid = "videoID";
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start !== "") {
if(ytid === document.getElementById('ytid')) {
ytid += '?start=' + start;
}
else {
ytid += '&start=' + start;
}
}
if (end !== "") {
if (ytid === document.getElementById('ytid')) {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
document.getElementById('embedcode').value = '<iframe ' + width + height +
'src=\"https://www.youtube.com\/embed\/' + ytid +
'\" frameborder=\"0\"><\/iframe>';
}
function clearall() {
document.getElementById('width').value = 550;
document.getElementById('height').value = 315;
document.getElementById('start').value = "";
document.getElementById('end').value = "";
}
The jsFiddle to play with what I need : https://jsfiddle.net/94150148/ybmkcyyu/
https://jsfiddle.net/ybmkcyyu/3/
EDIT:
Do not display start and end when value is 0
https://jsfiddle.net/ybmkcyyu/6/
EDIT2:
https://jsfiddle.net/ybmkcyyu/7/
if (start !== "") {
ytid += '?start=' + start;
}
if (end !== "") {
if (start == "") {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
You just need to get value of every fields, as int, then add it with the formula: ((hours * 60) + minutes ) * 60 + secondes
And you might ensure that the result is a number. (if user enter a char instead of a number, it should not display something wrong)
var starth = parseInt(document.getElementById('starth').value);
var startm = parseInt(document.getElementById('startm').value);
var starts = parseInt(document.getElementById('starts').value);
var endh = parseInt(document.getElementById('endh').value);
var endm = parseInt(document.getElementById('endm').value);
var ends = parseInt(document.getElementById('ends').value);
var start = (((starth * 60) + startm) * 60) + starts;
if(isNaN(start) || start === 0)
start = "";
var end = (((endh * 60) + endm) * 60) + ends;
if(isNaN(end) || end === 0)
end = "";
/* (...) */
JS is generally quite good at math.
sHour = document.getElementById('starth').value,
sMin = document.getElementById('startm').value,
sSec = document.getElementById('starts').value,
sTime = (sHour * 3600) + (sMin * 60) + sSec;
https://jsfiddle.net/link2twenty/ybmkcyyu/4/

cant figure out how to get the return showing .toFixed(2) amount without error

The script works great for adding items on invoice however i cant figure how to convert the data using .toFixed(2) to show $10.00 instead of 10. I get an error every time I try to add .toFixed(2) . thank you
<script type="text/javascript">
function myFunction() {
var answer = document.getElementById('total');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat("0" + x.value) + parseFloat("0" + y.value) + parseFloat("0" + z.value) + parseFloat("0" + w.value);
}
function myFunction1() {
var answer = document.getElementById('total');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
thetot.value = parseFloat("0" + answer.value) + parseFloat("0" + taxt.value);
if (thetot > "0") {
{
//function myFunction2()
var taxt = document.getElementById('taxtot');
var tx1 = document.getElementById('tax1');
var tx2 = document.getElementById('tax2');
var tx3 = document.getElementById('tax3');
var tx4 = document.getElementById('tax4');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var answer = document.getElementById('total');
taxt.value = parseFloat("0" + tx1.value) * ("0" + x.value) + parseFloat("0" + tx2.value) * ("0" + y.value) + parseFloat("0" + tx3.value) * ("0" + z.value) + parseFloat("0" + tx4.value) * ("0" + w.value);
}
}
}
</script>
Presumably your controls are in a form, so you can reference them simply using their name in the form. You can also convert strings to numbers using unary +:
function myFunction(formId) {
var f = document.getElementById(formId);
var answer = f.total;
var x = +f.itemprice1.value;
var y = +f.itemprice2.value;
var z = +f.itemprice3.value;
var w = +f.itemprice4.value;
var taxt = f.taxtot;
var thetot = f.thetot;
// Presumably here is where you want to use toFixed
answer.value = '$' + (x + y + z + w).toFixed(2);
}
function to_dollar_string(amount)
{
return "$" + amount.toFixed(2);
}
to_dollar_string(10);
=> "$10.00"
to_dollar_string(10.567);
=> "$10.57"

Categories