I'm trying to create two number counters that can increment and decrement the other counter in real-time. Also I don't know Javascript too well.
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">
If counter1 is increased, counter2 should be decreased, and vice versa; they are basically the inverse of each other. I've tried to implement some Javascript but it's not going well and I'm unsure of how to implement both incrementing and decrementing at the same time.
<script type="text/javascript"> //some non-working example code
function count() {
var counter1 = document.getElementById('counter1').value;
var counter2 = document.getElementById('counter2').value;
document.getElementById('counter2').onclick = function() { //onclick doesn't take into account if the input was increased or decreased.
counter2++;
counter1--;
}
document.getElementById('counter1').onclick = function() {
counter1++;
counter2--;
}
}
count();
</script>
Two major problems:
Assigning an input's value to a variable does not create a reference, it creates a copy. That means it isn't going to modify the number stored in the input, just the copied variable that you created.
You shouldn't use the click event. You should use the change event since it will fire whenever the value changes.
Finally, you can track the previous value of each input and compare it against the new value to determine if it increased or decreased. Even more simply, you can calculate the difference between those values and subtract that difference from the other inputs value.
var counter1 = document.getElementById('counter1');
var counter2 = document.getElementById('counter2');
var prevCounter1 = counter1.value;
var prevCounter2 = counter2.value;
counter1.addEventListener('change', function() {
var value1 = parseInt(counter1.value);
var value2 = parseInt(counter2.value);
var delta = value1 - prevCounter1;
counter2.value = value2 - delta;
prevCounter1 = value1;
});
counter2.addEventListener('change', function() {
var value1 = parseInt(counter1.value);
var value2 = parseInt(counter2.value);
var delta = value2 - prevCounter2;
counter1.value = value1 - delta;
prevCounter2 = value2;
});
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">
Simply..
console.log(counter1);
10
What you can understand here, is that you are assigning the value of document.getElementById('counter1').value to counter1, and not the element.
Proper USE
You should use something like :
counter1 = document.getElementById('counter1');
And to update it :
counter1.value++;
Minimalist CODE :
counter1 = document.getElementById('counter1');
counter2 = document.getElementById('counter2');
counter2.onclick = function() { counter2.value++; counter1.value--; };
counter1.onclick = function() { counter1.value++; counter2.value--; };
Here is a working fiddle, that as you change one input, it will update the other input.
https://jsfiddle.net/ctor9qk3/
Code :
Html:
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">
Javascript:
var counter1 = document.getElementById("counter1");
var counter1Value = counter1.value;
var counter2 = document.getElementById("counter2");
var counter2Value = counter2.value;
counter1.addEventListener('change', function() {
var amountOfChange = diff(this.value,counter1Value);
counter1Value = this.value;
counter2Value = counter2.value = parseInt(counter2Value - amountOfChange);
}, false);
counter2.addEventListener('change', function() {
var amountOfChange = diff(this.value,counter2Value);
counter2Value = this.value;
counter1Value = counter1.value = parseInt(counter1Value - amountOfChange);
}, false);
function diff (a, b) { return a - b }
This should work:
var ConnectedCounter = (function ConnectedCounter(selector) {
var connectedCounter = {
element: null,
value: 0
};
var self = {
element: null,
value: 0
};
function init() {
self.element = document.querySelector(selector);
if(self.element) {
self.value = parseInt(self.element.value);
connectedCounter.element = document.querySelector(self.element.dataset.target);
}
if(connectedCounter) {
connectedCounter.value = parseInt(connectedCounter.element.value);
['keyup', 'mouseup'].forEach(event => self.element.addEventListener(event, onUpdate));
['keyup', 'mouseup'].forEach(event => connectedCounter.element.addEventListener(event, onUpdate));
}
}
function onUpdate(event) {
var target = event.target;
var currentValue = +target.value;
var connectedTarget = null;
if(target === self.element) {
target = self;
connectedTarget = connectedCounter
}
else if(target === connectedCounter.element) {
target = connectedCounter;
connectedTarget = self;
}
currentValue = isNaN(currentValue)? target.value: currentValue;
connectedTarget.element.value = connectedTarget.value += (target.value > currentValue? 1: -1)*Math.abs(currentValue - target.value);
target.value = currentValue;
}
init();
return {
element: self,
connected: connectedCounter
}
})
document.addEventListener('DOMContentLoaded', function(e) { var x = new ConnectedCounter('#counter1')});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="number" step="1" value="10" name="counter1" id="counter1" data-target="#counter2">
<input type="number" step="1" value="10" name="counter2" id="counter2">
<script src="script.js"></script>
</body>
</html>
After you change a variable you have to set it in the DOM e.g. through document.getElementById('counter1').value = counter1; To get the changes of the inputs the click event works but I would prefer to listen for change events.
UPDATE I have to come up with a slightly more elegant solution. When one value should increase while the other is decreased the sum of both values will be the same. So it's just easier to initially sum up the values and afterwards calculate the second value by substracting the first (changed) value from the sum:
var input1 = document.getElementById('counter1');
var input2 = document.getElementById('counter2');
var sum = parseInt(input2.value) + parseInt(input1.value);
function onChange(e) {
if (this===input1)
input2.value = sum - parseInt(input1.value);
else
input1.value = sum - parseInt(input2.value);
}
input1.onchange = onChange;
input2.onchange = onChange;
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">
You can try something like this:
var input1 = document.getElementById('counter1');
var input2 = document.getElementById('counter2');
var lastCounter1 = parseInt(input1.value);
var lastCounter2 = parseInt(input2.value);
input2.onclick = function() {
var counter2 = parseInt(input2.value);
var counter1 = parseInt(input1.value);
counter1 += (lastCounter2 - counter2);
input1.value = counter1;
lastCounter2 = counter2;
lastCounter1 = counter1;
}
input1.onclick = function() {
var counter1 = parseInt(input1.value);
var counter2 = parseInt(input2.value);
counter2 += (lastCounter1 - counter1);
input2.value = counter2;
lastCounter1 = counter1;
lastCounter2 = counter2;
}
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">
Related
I would like to ask about the function that I made a slider that can display the value!
But I want to be able to swipe, and the numbers can change instantly, instead of stopping to display the numbers, how should this be rewritten?
I really need everyone's help, thank you in advance.
var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('change', function(event) {
var sliderValue = event.target.value;
var maxValue = 2000;
var coef = 18;
var calc;
calc = maxValue - (sliderValue * coef);
result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">
Change your event listener from change to input.
var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('input', function(event) { //changed to input here
var sliderValue = event.target.value;
var maxValue = 2000;
var coef = 18;
var calc;
calc = maxValue - (sliderValue * coef);
result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">
I have this slider in HTML and I was wondering how to check if the previous value of the slider is equal with the current value. Please if you know how to do this let me know. Thanks for your time.
var target = document.getElementById("myTarget");
let previous;
function foo(myValue) {
//console.log(myValue);
//Update SPAN
target.innerHTML = myValue; //EXPECTED = CURRENT VALUE
console.log(previous);
if(previous === myValue){
//Statements
console.log("same");
}else{
//Statemets
//previous = myValue;
console.log("different");
}
}
<input id="mySlider" type="range" value="0" min="0" max="5" step="1" oninput="foo(this.value);">
<span id="myTarget">0</span>
const slider = document.getElementById('mySlider');
const output = document.getElementById('output');
var initialValue = 2; // set however you want
slider.addEventListener('input', function (event) {
let outcome = "'"+initialValue+"' and '"+this.value+"' are ";
if( parseInt(this.value)===initialValue){
outcome+= "equal!"
} else{
outcome+= "not equal"
}
output.innerHTML = outcome
}, false);
<input id="mySlider" type="range" value="0" min="0" max="5" step="1"/>
<div id="output">
<em>Not run yet</em>
</div>
Thanks to #Martijn answer I was able to create a loop like this:
var slider = document.getElementById("slider-element_BV");
slider.addEventListener('input', function(event){
RAYS_CLASS.Ray_Techniques.RAYS_TECHNIQUES_MANAGER.BV().BV_REMOVE();
for(var i=this.min; i<=this.max; i++) {
if(parseInt(this.value) === i){
RAYS_CLASS.Ray_Techniques.RAYS_TECHNIQUES_MANAGER.BV().BV_Subdivide(i);
}
}
});
I should work with two input values that store only Integers when I increase the value of one, the other should decrease. This must stop if the second value hit 0.
The field that contains the value to be decreased is named with ID form_val62_1, and field that can be increased by the user input is called form_val63_1. I'm calling this function onChange() cause I need to pass the ID of the form (that's cause form fields are dynamically generated depending on a PHP array length).
function check(i) {
$("#form_val63_" + i ).change(function () {
var direction = this.defaultValue < this.value;
this.defaultValue = this.value;
var val;
val = parseInt($("#form_val62_" + i).val());
if (direction) {
if (val > 0) {
$('#form_val62_' + i).val(parseInt($(this).val()) - 1);
} else {
var thvar = $(this).val();
$(this).val(thvar - 1);
}
console.log("increase 503");
console.log(val);
} else {
$('#form_val62_' + i).val(parseInt($(this).val()) + 1);
console.log("decrease 503");
console.log(val);
}
});
}
Fiddle
I got many problems here, the first decrease one time, that increase with no reason (I know there is but can't see why).
Using the solution provided by #Ph0b0x i've updated my code as
var v = $("#form_val62_" + i).val(); //Let's say this is the value from PHP....
var preVal = 0;
$("#form_val62_" + i).val(v);
$("#form_val63_" + i).on("change keyup keydown", function(event) {
let currVal = parseInt($("#form_val63_" + i).val());
console.log(preVal);
console.log(currVal);
if (currVal == 0) {
preVal = 0;
$("#form_val62_" + i).val(v);
} else if (currVal <= v) {
$("#form_val62_" + i).val((v - currVal) == 0 ? 0 : (v - currVal));
preVal = currVal;
} else {
$("#form_val63_" + i).val(v);
}
});
Now I can increase the result but when i try decrease the each value remain 0.
I guess, if i understood correctly, i will keep track of the previous value on the second input then i will start decreasing the first one until it reaches 0 and increase it until it reaches 10? Fiddle
HTML
<form>
<input id="form_val62_1" type="number" min="0" value="10" />
<input id="form_val63_1" type="number" min="0" value="0" />
</form>
JS
var v = 13; //Let's say this is the value from PHP....
var preVal = 0;
$("#form_val62_1").val(v);
$("#form_val63_1").on("change keyup keydown", function(event) {
let currVal = parseInt($("#form_val63_1").val());
console.log(preVal);
console.log(currVal);
if (currVal == 0) {
preVal = 0;
$("#form_val62_1").val(v);
} else if (currVal <= v) {
$("#form_val62_1").val((v - currVal) == 0 ? 0 : (v - currVal));
preVal = currVal;
} else {
$("#form_val63_1").val(v);
}
});
Edit: I have updated my code based on your comment. Please see this Fiddle
So bind change event handlers on both elements. I would just use data attributes so you do not have to worry about selecting by ids to bind between both.
$('[data-num-grp]').on('input', function () {
// input that was interacted with
const inp1 = $(this);
// get the group number
const grp = inp1.data('num-grp')
// select the other element with the grp
const inp2 = $('[data-num-grp="' + grp + '"]').not(inp1);
// alter the other element so it's value changes
inp2.val(this.max - this.value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-num-grp="1" min="0" max="10" value="10"/>
<input type="number" data-num-grp="1" min="0" max="10" value="0"/>
<br/>
<input type="number" data-num-grp="2" min="0" max="10" value="10"/>
<input type="number" data-num-grp="2" min="0" max="10" value="0"/>
hello i was just wondering if there is anyway to get an input value to change / use it for the healLevel = 70% i give it a try but i'm new to this and fail.
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = 70;
HEAL1 = function() {
if (checkbox1.checked) {
heal.attributes.class.value = 'hud-shop-item';
useHeal.dispatchEvent(up);
heal.click();
}
};
HEAL2 = function() {
if (checkbox2.checked) {
petHeal.attributes.class.value = 'hud-shop-item';
usePetHeal.dispatchEvent(up);
petHeal.click();
}
};
script = function(e) {
if (e.keyCode == 82) {
HEAL1();
HEAL2();
}
};
document.addEventListener('keydown', function(e) {
script(e);
});
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
if (parseInt(mutations[0].target.style.width) < healLevel) {
HEAL1();
HEAL2();
}
});
});
observer.observe(healthBar, {
attributes: true,
attributeFilter: ['style']
});
})();
<input type="number" min="1" max="100" value="70">
this is what i have tried this but didn't seen to work any ideas why i failed ?
i tried using document.querySelector what am i doing wrong?
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
var elem = document.querySelector('input[type="number"]');
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = elem.value;
<input type="number" min="1" max="100" value="70">
HTML
<input type="number" min="1" max="100" value="70" id="healRate" onchange="updateHealLevel()">
JS
var healLevel = document.getElementById("healRate").value;
function updateHealLevel(){
healLevel = document.getElementById("healRate").value;
}
EDIT
Updated so that a change to the input value will update the healLevel.
To have the value change with the input, you must simply add an onchange event on the HTML component so that when the user changes this input, it will run the code which will update the healLevel.
I have two number inputs, what I want to do is to get dynamially the total price.
The problem is that when I decrease the number its still adding and doesn't work correctly. Actually my brain cannot imagine any way to code it correctly. Could someone give me any clue please?
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0
$('#open').on("change", function() {
totalPrice = totalPrice + ($("#open").val() * openPrice);
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPrice = totalPrice + ($("#vip").val() * vipPrice);
$("#doZaplaty").html(totalPrice);
});
</script>
Because totalPrice = totalPrice + ($("#open").val() * openPrice); will add up previous result, as I commented.
However, you have 2 different total to take into account, so it's not easy to keep the state with only one total, because you need to subtract the previous result ,or calculate the change from previous value.
Instead, you can have 2 different total, like openTotal for result on #open and vipTotal on result for #vip, then you can use openTotal = ($("#open").val() * openPrice); to get the current state. And when you need to output the result, use $("#doZaplaty").html(openTotal + vipTotal); to show the final total.
var vipPrice = 290;
var openPrice = 80;
var openTotal = 0;
var vipTotal = 0;
$('#open').on("change", function() {
// As the totals are separated, we just need to get its current values computed.
openTotal = ($("#open").val() * openPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
$('#vip').on("change", function() {
vipTotal = ($("#vip").val() * vipPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Because you always add to totalPrice. Try this instead (untested):
<script>
var totalPrice = 0
function GetTotalPrice(vipNum,openNum){
var vipPrice = 290;
var openPrice = 80;
var total = vipNum * vipPrice + openNum * openPrice;
return total;
}
$('#open').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
</script>
Please tyr by this simple way
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Set 2 hidden fields to store temp calculation value
<input type="hidden" name="totalPriceopenTemp" id='totalPriceopenTemp' value="0">
<input type="hidden" name="totalPricevipTemp" id='totalPricevipTemp' value="0">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0;
var totalPriceopenTemp = 0;
var totalPricevipTemp = 0;
$('#open').on("change", function() {
totalPriceopenTemp = ($("#open").val() * openPrice);
$("#totalPriceopenTemp").val(totalPriceopenTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPricevipTemp = ($("#vip").val() * vipPrice);
$("#totalPricevipTemp").val(totalPricevipTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
</script>
I think It will work for you