javascript get and use an input value - javascript

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.

Related

Checkbox disabling an input

I want to make it so when the user clicks the checkbox , the player Two input goes disabled. My problem is that the input remains disabled in both cases, doesn't matter if checkbox is checked or not.
const Initialization = (function() {
p1 = '';
p2 = '';
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value)
})
if (checkAI.checked = true) {
playerTwo.disabled = true;
} else {
playerTwo.disabled = false;
}
return {
p1,
p2,
}
})();
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />
worked by adding an eventListener to the checkbox.
checkAI.addEventListener('click',()=>{
if(checkAI.checked){
playerTwo.disabled = true;
}else{
playerTwo.disabled = false;
}
})
If you want to react on checkbox change you need to add event listener on this input. For example onclick or onchange. Take care to use comparaison operator in your if test checkAI.checked === true. You can find a JSFiddle
Event on checkbox input
You need an event handler and to test equality using == or ===
Here is a simpler version
const Initialization = function() {
const Player = str => console.log(str);
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
let p1 = '';
let p2 = '';
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value || "computer")
});
checkAI.addEventListener('click', (e) => {
const chk = e.target.checked;
playerTwo.disabled = chk;
if (chk) playerTwo.value="";
})
};
Initialization()
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />
You can accomplish this reactiveness by listening for the change event on the checkbox element and updating the input state accordingly:
const Initialization = (function() {
p1 = '';
p2 = '';
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value)
})
// listen for change event on checkbox
checkAI.addEventListener('change', () => {
// set playerTwo input to current checkbox state
playerTwo.disabled = checkAI.checked
})
return {
p1,
p2,
}
})();
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />

How to check html slider values in Javascript? (either value-1 or value+1)

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);
}
}
});

Disable button only when text input is 0

I have the following code:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
if (total.value > 1) {
console.log('enabled');
document.getElementById('btn-decrement-total').enabled = true;
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
total.value--;
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
The 'decrement' button seems to work and will disable itself when conditions are met.
But the 'increment' button doesn't seem to re-enable the 'decrement' button. Anyone knows why and how to solve this?
There's no enabled attribute, you should use disable="false" :
document.getElementById('btn-decrement-total').disabled = false;
Instead of:
document.getElementById('btn-decrement-total').enabled = true;
_______________________________________________^^^^^^^
Working sample:
var total = document.getElementById('total--input');
document.getElementById('btn-increment-total').addEventListener('click', function() {
total.value++;
if (total.value > 0) {
console.log('enabled');
document.getElementById('btn-decrement-total').disabled = false;
}
});
document.getElementById('btn-decrement-total').addEventListener('click', function() {
total.value--;
if (total.value == 0) {
console.log('disabled');
document.getElementById('btn-decrement-total').disabled = true;
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
enabled isn't a valid attribute, use disabled = false instead
You need to assign the input in an var/let or const.
try this way:
const total = document.querySelector("#total--input");
I had to add an return statement and change some lines of code but this should work.
const disableBtn = function (id, mode) {
document.getElementById(id).disabled = mode;
};
document.getElementById('btn-increment-total').addEventListener('click', function () {
let total = document.getElementById('total--input');
if (total.value >= 0) {
disableBtn('btn-decrement-total', false);
}
total.value++;
});
document.getElementById('btn-decrement-total').addEventListener('click', function () {
var total = document.getElementById('total--input');
total.value--;
if (total.value <= 0) {
disableBtn('btn-decrement-total', true);
return
}
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">
Try to parse the value from the input element to integer before comparing values...
var n1 = Number(document.getElementById('input_element').value).
Then you can check if it meets the condition

Dynamic input for number counters in Javascript

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">

Get text when copying from input

<input type="text"> event: <span id="result"></span>
<script>
var input = document.body.children[0];
input.oncopy = function(e) {
debugger
e = e || event;
// document.getElementById('result').innerHTML = e.type +' '+input.value;
// return false;
}
I want get text when copying .It is possible?
Just try with:
input.oncopy = function(e) {
var value = this.value.substring(this.selectionStart, this.selectionEnd);
}
demo

Categories