I'm trying to validate that two range inputs who filter age do not go over one another. I can't find a way to have it done properly without the sliders behaving erratically, jumping from 0 to 50, and things like that.
I've tried different approaches (pure JS) with similar results:
if(input1.value >= input2.value || input2.value <= input1.value){
input1.value = toString(input2.value - 1);
input2.value = toString(input1.value + 1);
}
This one makes the sliders jump back to 50. I can't remember what else I've tried, but all do sort of the same thing. Either jump back to 50, or the minimumRange jump from 2 or 3 to 100.
I'd rather not use jQuery if at all possible
Here's the fiddle with the whole thing:
JSfiddle Validation and filters
Thank you!
This is how the function looks like now:
function filtroEdad(input1, input2) {
var edadMin = Number(input1.value);
var edadMax = Number(input2.value);
if(edadMin >= edadMax){
input1.value = (edadMax - 1).toString();
}
if(edadMax <= edadMin){
input2.value = (edadMin + 1).toString();
}
Thank you, #RaphaMex !!
Can't reproduce your issue in your fiddle, but I already see 2 issues in your code:
if input1.value is "50", then input1.value + 1 will be "501"
toString() should be called on numbers: 50.toString()
So your code should look like:
var minEdad = Number(input1.value),
maxEdad = Number(input2.value);
if(minEdad >= maxEdad) {
// Decide here what to do, for example
input1.value = (maxEdad - 1).toString();
}
Related
Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))
I have an image with a couple of arrows either side to increment/decrement the image filename. Here's the left arrow code:
$('#sidebar-b').on("click", "#lar", function() {
var num = parseInt($('#main-img').attr('src').match(/(\d+)/)[1], 10);
if (num > 1) {
$('#main-img').attr('src', $('#main-img').attr('src').replace(/\d+/, function(val) {
return parseInt(val)-1
}));
}
});
And the right is very similar.
$('#sidebar-b').on("click", "#rar", function(){
var num = parseInt($('#main-img').attr('src').match(/(\d+)/)[1], 10);
if (num < $('#scroller').children().length) {
$('#main-img').attr('src',$('#main-img').attr('src').replace(/\d+/, function(val) {
return parseInt(val)+1
}));
}
});
Works excellent when the images are in "images/" but if they are in "images/h3/" or any directory with a number, every time I click the arrows it simply increments the directory name instead (images/h3/1.jpg, images/h4/1.jpg etc.)
This is obviously no good.
Tried changing the regex, probably be better if it selected characters after the last / or before a period.
Could maybe even use id.lastIndexOf('/')?
I've been coding all day and my brain is just fried at the moment, so I'm going to give my eyes a rest and have a cup of tea.
Hopefully one of you amazing people will point out the obviousness of where I am going wrong.
Currently everything just looks like scrambled digits to me and I can't see the wood for the trees!
You don't really need regex in this case:
$('#sidebar-b').on("click", "#lar", function() {
var s = $('#main-img').attr('src') ;
var slashI = s.lastIndexOf('/'),
dotI = s.lastIndexOf('.') ;
var num = parseInt(s.substring(slashI + 1, dotI)) ;
if (!isNaN (num)) {
$('#main-img').attr('src', s.substring(0, slashI + 1) + (num - 1) + s.substring(dotI));
}
});
You need to use a positive lookahead based regex. Now this would increments the number which exists only before to the extension.
$('#sidebar-b').on("click", "#lar", function(){
var num = parseInt($('#main-img').attr('src').match(/(\d+)(?=\.[^\/.]*$)/)[1], 10);
if (num > 1) {
$('#main-img').attr('src',$('#main-img').attr('src').replace(/\d+(?=\.[^\/.]*$)/,
function(val) { return parseInt(val)-1}));
}
});
Try .match with RegExp /\d+\./
var url = "images/h4/1.jpg";
console.log(parseInt("images/h4/1.jpg".match(/\d+\./), 10));
jsfiddle is here --> http://jsfiddle.net/diabetesjones/015k1tjn/5/
here's an example of one that does work:
http://jsfiddle.net/Ahopefulmachine/dkhj8o38/
Regarding the second jsfiddle (not mine), I don't quite get why his works without using document.getElementById on the button.
i feel like my problem is in the click function itself of :
document.getElementById('mainButton').onclick = function () {
thanks :)
working now: http://jsfiddle.net/doniyor/015k1tjn/9/
you had document.getElementByID which should be document.getElementById
AND
you didnot convert strings to int like numberOne = parseInt(numberOne, 10); where 10 is radix for decimal.
you had question == ADD which should be question == 'ADD'
There are three things wrong with your code:
It's getElementById not getElementByID (case-sensitive).
You didn't convert the strings you get from the input to numbers. You can do this easily by adding a + in front of the document.getElementById('number1').value;
You were doing comparisons against variables, not strings. Ex question == ADD instead of question == 'ADD'
See corrected jsFiddle example
document.getElementById('mainButton').onclick = function () {
//Getting values of inputs and saving them to variables
var numberOne = +document.getElementById('number1').value;
var numberTwo = +document.getElementById('number2').value;
//Setting values of the equations
var addition = (numberOne + numberTwo);
var subtraction = (numberOne - numberTwo);
var multiplication = (numberOne * numberTwo);
var division = (numberOne / numberTwo);
//Prompting user for their desired equation
var question = prompt("Do you wish to ADD, SUBTRACT, MULTIPLY, or DIVIDE?").toUpperCase();
//If statement to show the proper equation based on the user's prior prompt
if (question == 'ADD') {
alert('I added the shit out of those numbers for you - turns out it is ' + addition);
} else if (question == 'SUBTRACT') {
alert('Did some of this, some of that, some minusing - your answer is ' + subtraction);
} else if (question == 'MULTIPLY') {
alert('Yeah, I multipled the numbers, big whoop, wanna fight abouddit? the answers over there --> ' + multiplication);
} else if (question == 'DIVIDE') {
alert('This ones my favorite, I love a good division - ' + division);
};
};
I'm attempting to build an app that calculates sales metrics. I have run into an unusual problem in my build.
Part of the app allows users to increase/decrease a variable by 5% and then see how that will effect an overall metric. It also allows the user to see the percentage increase/decrease.
I have the functionality working roughly as intended, however if I enter a number lower than 20 into the input and then try in increase it with my incrementing function it only increments once and then stops.
If the number I enter into the input is 20 or greater it increments in the intended way.
Below is my angular code:
function controller ($scope) {
$scope.firstNumber = 0;
$scope.firstPercent = 0;
$scope.increase = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A + B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent + 5;
}
};
$scope.decrease = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A - B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent - 5;
}
};
I can't see anything wrong with my maths, my thinking is that perhaps I'm approaching angular in the wrong way. However I'm not sure.
I have put together a fiddle that shows the full code.
jsFiddle
I have updated the fiddle to use parseFloat. Seems like the numbers are incrementing now.
var A = parseFloat(id);
http://jsfiddle.net/kjDx7/1/
The reason why it was working with values above 20 was that it was just reading the part before decimals each time it tried to increase. So 20 became 21 and 22.05 and so on. As long the the value before decimal kept changing, it showed different (but incorrect) answers.
On the other hand, 10 became 10.5 which when parsed yielded 10. As you can see, this cycle continued endlessly.
The reason why you face the issue is because 5% of anything less than or equal to 20 is less than or equal to 1.
When you parseInt() the value, you always end up with the same number again.
Take 15 for example.
5% of 15 = 15.75
After parseInt(), you get the value 15 again.
You use the same value to increment / decrement each time.
Hence for values below 20, you don't get any changes.
As #Akash suggests, use parseFloat() instead - or why even do that when the value that you get is float anyway
I made a fork of your fiddle. I'm not completely sure what you want to achive.
Take a look at this fiddle.
$scope.increase = function() {
$scope.firstPercent = $scope.firstPercent + 5;
var A = $scope.firstNumber;
var B = (A / 100) * $scope.firstPercent;
var C = A + B;
$scope.firstNumberWithPercent = C;
};
update
After posting, i see that question is already answered. But is this what you really want? When you hit increase, it takes 5 % off of the number in the input field. That is ok, but when you hit decrease after that, it takes 5 % off the number in the same field. So your starting point is different.
100 + 5/100 = 105
105 - 5/105 = 99,75
Hey again everyone. Yet again i am having some problems with trying to get the match correct on this Excel Spreadsheet to JavaScript conversion.
Here is the excel formula:
=IF(IF($B$7=TRUE,$B$28/$B$10,$B$28/$B$5)>1,1,IF($B$7=TRUE,$B$28/$B$10,$B$28/$B$5))
WHERE
B7 = TRUE
B28 = 76800
B10 = 892015
B5 = 999500
And this is my JavaScript i have so far:
function percent(x) { return Math.round((x-0)*100) + '%'; }
if($('#section179').is(':checked'))
{
var percentRepaid = $("#rev3DScanYear").val() / $("#section179Real").val();
if (percentRepaid > 1)
{
$("#paymentCashPer").val('100.00');
}else
{
percentRepaid = $("#rev3DScanYear").val() / $("#SalePrice").val();
$("#paymentCashPer").val(percent(percentRepaid));
}
}else
{
//to be done
}
WHERE
rev3DScanYear = 76800
SalePrice = 999500
section179Real = 892015
For the JavaScript code i keep getting a value of 8% and i should be getting a value of 8.61% as it has on the spreadsheet.
As always, any help would be great! :o)
David
Math.round((x-0)*100) makes x an integer.
You could try Math.round(((x-0)*100)*100)/100 which makes the x = 8.609720... into x=861 and then divides it to get the x=8.61 you're looking for, which is what they would suggest here.
...Also, not really sure why you're subtracting 0 from x...?
Ok, so I've been looking at this again, and I think I didn't look deeply enough the first time.
The logic, if I understand it, is this:
If Section179 is checked then Divisor is Section179Real, else it is SalePrice.
Give me the smaller of 1.00 or (rev3DScanYear / Divisor).
If that's correct, you can do it in excel with =MIN(1,$B28/IF($B$7=TRUE,$B$10,$B$5)) (same references), which means that the following should do what you want it to:
var Divisor = $("#SalePrice");
if($('#section179').is(':checked'))
{
Divisor = $("#section179Real");
}
$("#paymentCashPer").val(Math.round(100*(Math.min(1, $("#rev3DScanYear")/Divisor)*100)/100;