Combining change and keyup - javascript

I have a form in which I am calculating cost for a product. It depends on both an input value they put in and a select they choose.
Is there a way to combine the change and keyup events into one cleaner segment?
My code is as followed:
https://jsfiddle.net/qrv57qtu/
$('#input').keyup(function(){
var x = $('#input').val();
var y = $('#select').val();
if (y == '5') {
var z = 5;
}
else if (y == '10') {
var z = 10;
}
var z = x * y;
$('#total').html(z);
});
$('#select').change(function(){
var x = $(this).val();
var y = $('#input').val();
if (x == '5') {
var z = 5;
}
else if (x == '10') {
var z = 10;
}
var a = y * z;
$('#total').html(a);
});
Thank you.

You can use a single comma-delimited selector to get both elements. Then if you use the on() method you can provide a space-delimited string containing the event names you want to bind to, like this:
$('#input, #select').on('keyup change', function() {
var x = $('#input').val();
var y = $('#select').val();
if (y == '5') {
var z = 5;
}
else if (y == '10') {
var z = 10;
}
var z = x * y;
$('#total').html(z);
});
Also note that the if condition in your logic is entirely redundant as you overwrite the value of z at the end anyway

Here's the working code:
$(document).on("keyup change", "#input, #select", function(){
var x = $('#select').val();
var y = $('#input').val();
if (x == '5') {
var z = 5;
}
else if (x == '10') {
var z = 10;
}
var a = y * z;
$('#total').html(a);})
https://jsfiddle.net/itsrikin/gaL237qg/

Related

can you help whi console log?

i need to count X and Y
but my console log dosent work, maybe problem in
if matches[i].includes(something) == "true"
var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
let x = 0;
let y = 0;
if (matches[i].includes("w") == "true") {
x = x - matches[i];
console.log(x);
}
if (matches[i].includes("e") == "true") {
x = x + matches[i];
console.log(x);
}
if (matches[i].includes("n") == "true") {
y = y + matches[i];
console.log(y);
}
if (matches[i].includes("s") == "true") {
y = y - matches[i];
console.log(y);
}
}
You need to to use toLowerCase() since includes() is case sensitive.
Also, no need to compare includes() == "true" since it returns a boolean and it is enough for the if condition (which will execute the next block statement based on that boolean condition)
var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
const match = matches[i].toLowerCase();
let x = 0;
let y = 0;
if (match.includes("w")) {
x = x - matches[i];
console.log(x);
}
if (match.includes("e")) {
x = x + matches[i];
console.log(x);
}
if (match.includes("n")) {
y = y + matches[i];
console.log(y);
}
if (match.includes("s")) {
y = y - matches[i];
console.log(y);
}
}

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.
What should I do in order to get the code to recognize 0 as a value?
var x =
this.getField("1_7").value;
var y =
this.getField("2_7").value;
var z =
this.getField("3_7").value;
var f = Math.floor((this.getField("Des Temp").value - 10) / 2);
var temp;
if(!x)
{
x = f;
}
if(!y)
{
y = f;
}
if(!z)
{
z = f;
}
if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;
if(f > temp)
f = temp;
if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}
O is a "falsy" value so
if(!x)
Is doing what it is supposed to do. The empty value is probably an empty string so you could do
if ( ! x.length )
instead.
$('#x').on( 'input', function() {
console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >
It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.
var x = 0;
var y = 5;
var z = 3;
var f = 10;
if(0)
{
console.log("0 is false");
}
if(1)
{
console.log("1 or any number != 0 is true");
}
if(x.length)
{
x = f;
console.log("x is not set");
}
if(y.length)
{
y = f;
console.log("y is not set");
}
if(y.length)
{
z = f;
console.log("z is not set");
}

Input validation only working once

I am trying to create a script that will take 2 inputs and calculate the sum. I would like both inputs to be validated before the calculation takes place - inputs must range between 0 and 10.
However when I input values over 10 in both fields (e.g. 50), I am only getting one validation error instead of two.
What could be wrong?
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
} else if (isNaN(y) || y < 0 || y > 10) {
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
} else {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
<p>Please input a number between 0 and 10:</p>
1st number:<input id="val01" required> <b id="validation1"></b> <br>
2nd Number:<input id="val02" required> <b id="validation2"></b> <br>
<button onclick="calc()">click</button><br /> sum = <span id="total">0</span>
You could use a flag and check it for the calculation.
Skip the else parts and use the flag instead.
var ok = true;
if (isNaN(x) || x < 0 || x > 10) {
ok = false;
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
}
if (isNaN(y) || y < 0 || y > 10) {
ok = false;
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
}
if (ok) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
If your first validation fails (if (...)), you do not execute the second validation (else if (...)) anymore.
Instead, run the validations separately from each other and only do the calculation if both succeed, e.g.:
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
var valid = true;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
valid = false;
}
if (isNaN(y) || y < 0 || y > 10) {
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
valid = false;
}
if(valid) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
You only get one validation because of the way your logic inside the if else statement is built.
You only go "inside" one of the three statements, because you're using if else if, when you need to go inside multiple ones, you can just use a sequence of if()
<script>
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
var invalidX = true;
var invalidY = true;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
invalidX = false;
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
}
if (isNaN(y) || y < 0 || y > 10) {
invalidY = false;
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
}
if (invalidX && invalidY) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
</script>
Hope that is what you were looking for. Notice that I also included two variables with booleans that control if the input is valid.
Remove the else if condition in your code for the second valida ation that u are doing.

Convert a number into sum of two other numbers so the difference is minimum

In Mars, there are only two denominations of currency ,x and y. A
Marsian goes to a bar and the bill is "z". Using x and y he has to pay
the bill. But the bar doesn't tender change, any extra money will be
taken as tips.
So write a function in JavaScript that helps the marsian to reduce the
tips.
The function takes in x, y, z and returns the amount of tip he has to
pay.
Example 1
Input: 2, 5, 109
Output: 0
Explanation: 21 coins of 5, and 2 coins of 2
Example 2
Input: 5, 7, 43
Output: 0
Explanation: 4 coins of 7, and 3 coins of 5
Example 3
Input: 15, 19, 33
Output: 1
Explanation: 1 coin of 15 and 1 coin of 19
Solution: I think this is level one DP problem, something like subset sum. Like for finding the optimal tip for the larger number, knowing the optimal tip for all the below numbers would help.
const coinA = 2
const coinB = 5
const sum = 13
var arr = [];
arr[0] =0;
console.log(getMyTip(coinA, coinB, sum));
function getMyTip(){
for(var i=1; i<= sum; i++){
var minA, minB;
if( i < coinA){
minA = coinA - i;
}else{
minA = arr[i - coinA];
}
if( i < coinB){
minB = coinB - i;
}else{
minB = arr [i - coinB]
}
arr[i] = Math.min(minA, minB);
}
return arr[sum];
}
Jsfiddle: https://jsfiddle.net/7c4sbe46/
But I'm not sure why it is not getting accepted. Please let me know if I'm missing something with the logic here.
It is more related to diophantine equations, i.e. is there a solution to a.x+b.y=z ? The answer is yes if z is a multiple of the greatest common divisor of x and y (called it gcd). If not, your tip will be the difference between 1. the smaller number divisible by gcd and greater than z
and 2. z.
Once you know the value of the tip, you can even easily know the number of x and y that you need by slightly modifying the value of z to (z+tip).
#include <stdio.h>
int main()
{
int curr1, curr2, bill;
scanf("%d %d %d",&curr1,&curr2,&bill);
int gcd, tip=0;
int x=curr1;
int y=curr2;
while(x!=y)
{
if(x > y)
x -= y;
else
y -= x;
}
gcd=x;
if((bill%curr1==0) || (bill%curr2==0) || (bill%(curr1 + curr2)==0)){
tip = 0;
} else if(bill>(curr1 + curr2) && (bill % gcd==0)) {
tip = 0;
} else if((curr1 + curr2) > bill){
if(curr2 > curr1){
tip = (bill % (curr2-curr1));
}else{
tip = (bill % (curr1-curr2));
}
}
printf("%d",tip);
return 0;
}
There is no need to use dp for this. Here is the simple solution -
// x -> first currency denomination
// y -> second currency denomination
// z -> total bill
var calculateTip = function(x,y,z) {
var xMax = Math.floor(z/x);
var tip = y;
if(xMax == 0) {
tip = (x-z) < (Math.ceil(z/y)*y - z) ? (x-z) : (Math.ceil(z/y)*y - z);
}
while (xMax>=0) {
var tempTip = xMax*x + Math.ceil((z-xMax*x)/y)*y - z;
if(tempTip < tip) {
tip = tempTip;
}
xMax--;
}
return tip;
}
var minimumTip = function(x,y,z) {
if(x>y) {
return calculateTip(x,y,z);
} else {
return calculateTip(y,x,z);
}
}
console.log(minimumTip(2, 5, 109));
var findTip = function(x=2, y=5, z=13){
var x = x;
var y = y;
var z = z;
var tip ;
var temp1 = x;
var temp2 = y
function findNumber(num,total){
if(num > total){
return num-total;
}
else{
var q = Math.floor(total/num);
return ((q+1)*num)-total;
}
}
function findMin(a,b,c){
var min ;
if(a<b && a<c){
min = a
}else{
if(b<c){
min = b;
}else{
min = c;
}
}
return min;
}
while(temp1!=temp2)
{
if(temp1 > temp2)
temp1 -= temp2;
else
temp2 -= temp1;
}
var factor =temp1;
if(z%x == 0 || z%y == 0 || z%(x+y) == 0) {
tip = 0;
}else if(z%factor == 0 && z>=x*y - x -y){
tip = 0;
}
else {
var minX= findNumber(x,z);
var minY = findNumber(y,z);
var minXY = findNumber(x+y,z);
console.log(minX,minY,minXY)
tip = findMin(minX,minY,minXY);
}
alert('the tip is '+ tip.toString());
return tip;
}
findTip(21, 11, 109);

Jquery array querying not working

So I have to pares through an array and it's multiple variables and input them on separate lines.
Here is the code:
while (array[x] != null) {
y = 0;
y = x;
alert(y + 'y');
setTimeout(function() {
if (y == 0 || y % 3 === 0) {
var namestring = array[y];
var namestring = namestring.replace('[','');
var namestring = namestring.replace('[','');
var namestring= namestring.replace('"', '');
var namestring= namestring.replace('"', '');
}
if (y % 2 != 0 || y % 3 != 0 && x > 0) {
var date = array[y]
var date = date.replace('"', '');
var date = date.replace('"', '');
}
if (x % 2 == 0 && x > 0) {
var text = array[y];
var text = text.replace('"', '');
var text = text.replace('"', '');
var text = text.replace("]", '');
var text = text.replace("]", '');
createcard(namestring,date,text);
}
}, 500);
if (x > 500) {
break;
};
x++;
alert(x + 'x');
}
The alerts are simply for debugging. Anyway, my variables, for example namestring gets returned as undefined. However, if I change the line to say array[0] instead of array[y], it works, even if y is set to 0...
You're assigning
y = 0;
and
y = x;
x appears to be undefined in that code snippet but maybe it is part of a larger batch of code. It basically looks like you're overwriting y with the value of x?

Categories

Resources