how to sync Range-type - javascript

I have 2 inputs as you see in my code if you type anything in the input/text it shows perfectly fine at range but not the other way around this is my problem
I am also open to completely different approaches to the problem any answer is accepted
Code Snippet:
var city = document.getElementById('city')
var cityrepeat = document.getElementById('cityrepeat')
var state = document.getElementById('state')
var staterepeat = document.getElementById('staterepeat')
function setCity() {
cityrepeat.value = city.value
}
function setd() {
city.value = cityrepeat.value
}
function setState() {
staterepeat.value = state.value
}
City
<input id="city" type="text" onKeyUp="setCity()" size=5/></br>
State
<input id="state" type="text" onKeyUp="setState()" size=5/></br>
City repeat
<input id="cityrepeat" type="range" min="1" max="100"onKeyUp="setd()"/></br>
State repeat
<input id="staterepeat" type="range"/>

Instead of onKeyUp="setd()" use onchange="setd()"
<input id="cityrepeat" type="range" min="1" max="100" onchange="setd()"/>
Or even better:
In order to make the value updating 'live', you can do this:
in the html:
<input id="cityrepeat" type="range" min="1" max="100" onmousedown="updating=true;setd()" onmouseup="updating=false"/>
in you script:
var updating = false
function setd() {
city.value = cityrepeat.value
if (updating){
requestAnimationFrame(setd)
}
}
var city = document.getElementById('city')
var cityrepeat = document.getElementById('cityrepeat')
var state = document.getElementById('state')
var staterepeat = document.getElementById('staterepeat')
var updating = false
function setCity() {
cityrepeat.value = city.value
}
function setd() {
city.value = cityrepeat.value
if (updating){
requestAnimationFrame(setd)
}
}
function setState() {
staterepeat.value = state.value
}
City
<input id="city" type="text" onKeyUp="setCity()" size=5/><br>
State
<input id="state" type="text" onKeyUp="setState()" size=5/><br>
City repeat
<input id="cityrepeat" type="range" min="1" max="100" onmousedown="updating=true;setd()" onmouseup="updating=false"/><br>
State repeat
<input id="staterepeat" type="range"/>

Try using onChange instead of onKeyUp on the slider.
<input id="cityrepeat" type="range" min="1" max="100"onChange="setd()"/></br>

Related

Prevent user from entering smaller value than previous input

I am student testing and learning new things. Right now I'm trying to make a GUI fan speed controller. While I have made the basic code, I want that the user cant enter smaller value than previous input.
Javscript code
// 30
var range3 = document.getElementById("range3");
var num3 = document.getElementById('num3');
range3.addEventListener('input', function (e) {
num3.value = e.target.value;
});
num3.addEventListener('input', function (e) {
range3.value = e.target.value;
});
// 40
var range4 = document.getElementById("range4");
var num4 = document.getElementById('num4');
range4.addEventListener('input', function (e) {
num4.value = e.target.value;
});
num4.addEventListener('input', function (e) {
range4.value = e.target.value;
});
// 50
var range5 = document.getElementById("range5");
var num5 = document.getElementById('num5');
range5.addEventListener('input', function (e) {
num5.value = e.target.value;
});
num5.addEventListener('input', function (e) {
range5.value = e.target.value;
});
function execute(){
document.getElementById("result").innerHTML = num3.value + " " + num4.value + " " + num5.value ;
}
HTML code
<input id="range3" type="range" min="0" max="100" value="0" />
<input id="num3" min="0" max="100" type="number" value="0" />
<input id="range4" type="range" min="0" max="100" value="0" />
<input id="num4" min="0" max="100" type="number" value="0" />
<input id="range5" type="range" min="0" max="100" value="0" />
<input id="num5" min="0" max="100" type="number" value="0" />
<button onclick="execute()">Click</button>
<p id="result"></p>

How to reset JavaScript code when input value is changed?

I would like for the code to change its answer when I change the value of the input.
So let's say instead of 10, I would like it to tell me how much HP (health points) I will have at level 15. Is there any way I can do this? I'm not that experienced in Javascript.
So right now I coded it to default to 10 on all stats. My website tells me that at level 10, I have 895.4 hp. The only problem is that it won't stay at 15 when I try to press enter. It will just revert back to 10. Pretty much useless. Is there any way to keep that number 15 when I press enter?
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
<form>
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a form submit event listener to the form element and prevent form submission there.
<form onsubmit="submitForm(event)">
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a submitForm function inside a script tag
function submitForm(event){
event.preventDefault();
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
}
So mainly I'm just adding eventListeners to trigger the function calculateHP on input/slider value change. The function calculateHP contains the same logic that you shared. I did this so that the eventListeners can callback the function.
Try the following:
const input = document.querySelector('.hp')
const slider = document.querySelector('.slider')
slider.addEventListener('change', calculateHP)
input.addEventListener('change', calculateHP)
function calculateHP(){
let multiplier = 1.06
let level = Number(input.value)
let HP = 500
for(let i = 0; i<level; i++){
HP = HP * multiplier
}
return console.log(HP)
}
<div>
<label>Level: </label>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>

How to subtract two div by their ID?

I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>

How to get the value of a range slider?

Can you please help me how to get values of a range slider in javascript?
<script>
$(function()
{
$('.slider').on('input change', function(){
$(this).next($('.slider_label')).html(this.value);
});
$('.slider_label').each(function(){
var value = $(this).prev().attr('value');
$(this).html(value);
});
})
</script>
<p><label for="range_size">Size: </label> <input type="range" name="size" class="slider" min="1" max="75" value="45">
<span class="slider_label"></span></p>
<p><label for="range_width">Width: </label> <input type="range" name="width" class="slider" min="1" max="6" value="1">
<span class="slider_label"></span></p>
I am trying to get like this :
<script type="text/javascript">
function calculate () {
var size = document.getElementById ("size").value;
alert(size);
</script>
But it doesn't show any alert. Can you please help me?
Using value does work :
let p = document.getElementById("val")
let range = document.getElementById("slide")
let changeVal = () => {
p.textContent = range.value
}
changeVal()
range.onchange = changeVal
<input id="slide" type="range" min="0" max="100"/><p id="val"></p>
as B001ᛦ said in comment the problem is you forgot to add an id on your <input>
If you prefer you can also use names but you need to take care as name can be reused while Ids are unique
let p = document.getElementsByName("val")[0]
let range = document.getElementsByName("slide")[0]
let changeVal = () => {
p.textContent = range.value
}
changeVal()
range.onchange = changeVal
<input name="slide" type="range" min="0" max="100"/><p name="val"></p>
getElementsByName return a NodeList so you'll need to get the node you need from this list (the first one if you have only one)
as a side note value does exists on every input type

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

Categories

Resources