How to get the value of a range slider? - javascript

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

Related

How to give a change the value of a variable when radio button is checked?

I am currently trying to make a calculator using javascript and I have been able to add the what the user will input into textboxes and I am trying to change the value of a variable when a radio is checked. Is there any way to change the value of the variable when the ratio is checked?
Thanks in advance
let firstInput = document.querySelector('#firstInput');
let secondInput = document.querySelector('#secondInput');
let thirdInput = document.querySelector('#thirdInput');
let btnAdd = document.querySelector('button');
let result = document.querySelector('h1');
btnAdd.addEventListener('click', () =>{
let total = parseFloat(firstInput.value) + parseFloat(secondInput.value) +
parseFloat(thirdInput.value) + parseInt(genderReflection);
result.innerText = total.toFixed(3);
});
window.onload = function(){
var genderReflection = {
price: 5
}
var maleRelaxation = document.getElementById('Male');
Male.addEventListener('click' ,function(){
genderReflection.price += parseFloat(maleRelaxation.value)
})
}
<input type="number" id="firstInput">
<div id="calculator">
<input type="radio" id="Male" name="gender" value="5">
<label for="Male">Male</label>
<input type="radio" id="Female" name="gender" value="-161">
<label for="Female">Female</label>
</div>
<input type="number" id="secondInput">
<input type="number" id="thirdInput">
<button>ADD</button>
<h1>result</h1>
You could add an onClick="function_name(amount)" onto the inputs.
Where function name would add the variable to a (globally declared) list.
From there, the logic is yours.
Edit
Ofcourse, adding an eventlistener and getting the attribute as specified in comment above would probably be better. Saves typing. ;)
two errors:
1)place all the js code inside window.onload
2)to get the value out of genderReflection use generReflection.price
window.onload = function(){
let firstInput = document.querySelector('#firstInput');
let secondInput = document.querySelector('#secondInput');
let thirdInput = document.querySelector('#thirdInput');
let btnAdd = document.querySelector('button');
let result = document.querySelector('h1');
btnAdd.addEventListener('click', () =>{
let total = parseFloat(firstInput.value) + parseFloat(secondInput.value) +
parseFloat(thirdInput.value) + parseInt(genderReflection.price);
result.innerText = total.toFixed(3);
});
var genderReflection = {
price: 5
}
var maleRelaxation = document.getElementById('Male');
Male.addEventListener('click' ,function(){
genderReflection.price += parseFloat(maleRelaxation.value)
})
}
<input type="number" id="firstInput">
<div id="calculator">
<input type="radio" id="Male" name="gender" value="15">
<label for="Male">Male</label>
<input type="radio" id="Female" name="gender" value="-161">
<label for="Female">Female</label>
</div>
<input type="number" id="secondInput">
<input type="number" id="thirdInput">
<button>ADD</button>
<h1>result</h1>

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>

Slider to show a word based on a value

I have a slider that displays the active value beneath it. How do I change it from showing a number to showing a word depending on what the active value is?
Is it possible to change the value "1" to be the word "One"?
Here is the fiddle: https://jsfiddle.net/orv5sety/
Below is all I have:
HTML:
<input type="range" min="1" max="5" value="1" id="myRange">
<p><span id="demo"></span></p>
JS:
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
Any help would be greatly appreciated!
simply that
const nStr = 'zero one two three four five'.split(' ')
demo.textContent = nStr[ myRange.valueAsNumber ]
myRange.oninput=_=>
{
demo.textContent = nStr[ myRange.valueAsNumber ]
}
<input type="range" min="1" max="5" value="1" id="myRange" step="1">
<p id="demo"> </p>
You would need to have a mechanism to match the numeric value to the word representation - I would do it with an array and pass the numeric value to a function that returns the numeric string value.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = numberToString(slider.value);
slider.oninput = function() {
output.innerHTML = numberToString(this.value);
}
function numberToString(num) {
const numberStrings = ['One', 'Two', 'Three', 'Four', 'Five'];
return numberStrings[num-1]
}
<input type="range" min="1" max="5" value="1" id="myRange">
<p><span id="demo"></span></p>
Yet another...
<input type="range" min="1" max="5" value="1" id="myRange" oninput="demo.innerHTML=['One','Two','Three','Four','Five'][Number(this.value)-1];">
<p><span id="demo">One</span></p>
You should be able to achieve this by using the datalist element for the input type "range".
<input type="range" value="0" min="0" max="4" list="tickmarks" id="myRange">
<datalist id="tickmarks">
<option value="0" label="One">One</option>
<option value="1" label="Two">One</option>
<option value="2" label="Three">Two</option>
<option value="3" label="Four">Three</option>
<option value="4" label="Five">Four</option>
</datalist>
<p><span id="demo"></span></p>
Then you can pass the values using a simple function like you have written; selecting the option value by label:
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var datalist = document.getElementById("tickmarks").options
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = datalist[this.value].label
}

how to sync Range-type

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>

Save the values in array (and override for each update)

I'm having the trouble with saving the values as array.
I have such HTML code:
<div id="cn1" class="container cont container4">
<input id="slider1" type="range" class="slider slider1" min="0" max="5" value="1" step="1">
<input id="slider2" type="range" class="slider slider2" min="0" max="5" value="1" step="1">
<input id="slider3" type="range" class="slider slider3" min="0" max="5" value="1" step="1">
<input id="slider4" type="range" class="slider slider4" min="0" max="5" value="1" step="1">
<input id="slider5" type="range" class="slider slider5" min="0" max="5" value="1" step="1"></div>
5 containers with 5 sliders inside = 25 sliders.
Need to get the id and values for each sliders and save as
"sliders":[
{
"slider":"slider1",
"value":"1"
},
{
"slider":"slider2",
"value":"1"
}...
]
Here is the script to get the values for each slider:
slider = $('.slider');
var len = slider.length;
$(slider).change(function () {
bt = $(this).attr('id');
value = $(this).val();
save = '{"slider":"' + bt + '", "value":"' + value + '"}';
console.log('save', save);
})
.trigger('change');
}
So, i see in console 'save' for each slider.
I need to write each 'save' as array of values, then this data with be saved in json file and used for the other page.
I'm trying
function saveValues(){
var toSave = '"slide10" : {';
toSave += '"sliders":[';
for (var i=1;i<len;i++) {
toSave +=''+save+',';
}
toSave+=']';
return toSave+='}';
}
But it save the value for the last 'save' 25 times... :( Like this:
"sliders":[
{
"slider":"slider25",
"value":"1"
},
{
"slider":"slider25",
"value":"1"
}...
]
How can I save the values in array (and override for each change of the value of corresponding slider)?
You can do something like this:
//get all range type's
var sliders = document.querySelectorAll('[type="range"]');
//prepare array variable
var result = [];
//loop the sliders
for(var i=0, l=sliders.length; i < l; i++){
var slider = sliders[i];
//push the object with id and value in the array
result.push({
slider: slider.id,
value: slider.value
});
}
//display the result :)
console.log(result);
jsfiddle

Categories

Resources