HTML5 Slider with onchange function - javascript

I have a slider (input type range) that is supposed to run a function when the value is being changed. The function should then display the new value in a separate div container. After placing an alert in the function, I know that the function isn't being called, but after googling for an hour and trying a few different methods I just can't find the error.
Here's the HTML part:
<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">
<div id="sliderAmount"></div>
JavaScript:
// Slider
function updateSlider(slideAmount)
{
alert("error");
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}

It works, you just need to make sure that the JavaScript function is defined when the element is rendered, for example:
<script>
function updateSlider(slideAmount) {
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}
</script>
<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">
<div id="sliderAmount"></div>
See this demo: https://jsfiddle.net/Mmgxg/
A better way would be to remove the inline onchange attribute:
<input id="slide" type="range" min="1" max="100" step="1" value="10">
<div id="sliderAmount"></div>
And then add the listener in your JavaScript code:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
}
https://jsfiddle.net/PPBUJ/

Related

How to display input value on page in Javascript?

How to display input value on the website? I already tried to display it but when I change the value of the input, the display is still the same.
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
What you did puts the value of the input in the paragraphe on load. Plus you need an EventListener in order to track the input changes, like so:
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
rangeInput.addEventListener("input", ()=>{
valueInp.innerHTML = rangeInput.value;
})
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
rangeInput.addEventListener("input", () => {
valueInp.textContent = rangeInput.value;
});
valueInp.textContent = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>```
Provided that the <p> element for the value will always be following directly after your range element then the following script will take care of any number of range/value combinations:
document.querySelectorAll(".range")
.forEach(r=>r.addEventListener("input",update(r)));
function update(r){
const ur= ()=>r.nextElementSibling.textContent=r.value;
ur();
return ur;
}
<input type="range" min="1" max="100" value="40" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="20" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="30" step="1" class="range"/>
<p></p>
Try this :
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
range.addEventListener("change",()=>{
valueInp.innerHTML = rangeInput.value;
})
valueInp.innerHTML = rangeInput.value;
addEventListener here will be executed whenever value inside input tag is changed .
You need to wire-up an event-listener on the <input/> which then updates the <p class="value"> in the event-handler.
You can only wire-up event-handlers after DOMContentLoaded btw.
There are two main events you can listen to:
Use the 'input' event to respond to every change-in-value, even while the <input> element has focus.
Use the 'change' event to only respond to changes when the user has stopped interacting with the input.
BTW, you should use an <output> element instead of <p> for showing "output" values.
You should use id to select specific elements instead of .className selectors because class="" is not unique.
Never use innerHTML for showing text as it opens you up to XSS attacks.
For <output> you can set HTMLOutputElement.value.
For all other elements, use textContent.
Or innerText.
Like so:
window.addEventListener( 'DOMContentLoaded', onDomLoaded );
function onDomLoaded() {
const rangeInput = document.getElementById('myRangeInput');
const output = document.getElementById('myOutput');
// Show initial value immediately:
output.textContent = rangeInput.value;
// 'input' is the name of the event-type, not the <input> element name.
// you can also use 'change' instead.
rangeInput.addEventListener( 'input', e => {
output.textContent = rangeInput.value;
} );
}
<input id="myRangeInput" type="range" min="1" max="100" value="1" step="1" class="range"/>
<output id="myOutput" for="myRangeInput"></output>
If you want something really succinct, then just update the <output> dire use a named <output> the oninput="" attribute, like so:
<input id="myRangeInput" type="range" min="1" max="100" value="1" step="1" oninput="document.getElementById('myOutput').value = this.value;" />
<output id="myOutput" for="myRangeInput"></output>

Focus/unfocus an input on range slider handler's use

I have a form where the inputs values are controlled by range sliders. There's a calculation every time there's a new entry on each input which operates on focusout.
Though, the calculation doesn't work when only the range sliders are used. Is there a way to focus the inputs while using the range sliders? I can't change the way of calculation, because, it's on all the inputs. So, it has to be this way.
My form is bigger, but, here's an example of what I have:
<label class="va1">Option a price 1:<input id="a1" type="number"/></label>
<input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
<label class="va2">Option a price 2:<input id="a2" type="number"/></label>
<input type="range" id="slider-a2" min="0" max="100" step="1" value="0"><br>
<label>Result:</label><input id="a5" type="text" name="total_amt"/>
And here's the JS:
var opt_1 = document.getElementById("slider-a1");
opt_1.oninput = function() {
document.getElementById("a1").value = opt_1.value;}
var opt_2 = document.getElementById("slider-a2");
opt_2.oninput = function() {
document.getElementById("a2").value = opt_2.value;}
calculate = function(){
var optiona1, optiona2, resultss;
optiona1 = Number(document.getElementById("a1").value);
optiona2 = Number(document.getElementById("a2").value);
resultss = parseInt(optiona1)+parseInt(optiona2);
document.getElementById('a5').value = resultss;}
$('input[type=number]').on('focusout', calculate);

How to change the Volume of an audio object with html range slider?

hi this is the code I'm using to play a shoutcast cast stream works fine but not able to change the volume is this wrong I'm new at this.
<script>
function audioobject()
{
var link = new Audio('http://107.155.72.250:8000/;.mp3');
return link;
}
function startradio()
{
audioobject().play();
}
function changevolume(amount)
{
audioobject().setVolume(amount);
}
</script>
<input type="button" id="play" value="Play" onclick="startradio()"/>
<input type="range" id="vol" max="1" min="0" step="0.01" onchange="changevolume(this.value)"/>
The correct method to set the volume is audioobject.volume = VALUE
Here's a demo showing a similar setup as you want.
function changevolume(amount) {
var audioobject = document.getElementsByTagName("audio")[0];
audioobject.volume = amount;
}
<audio autoplay loop src="https://archive.org/download/animalsounds1/12wolveshowlfar.mp3"></audio>
<input type="range" id="vol" max="1" min="0" step="0.01" onchange="changevolume(this.value)" />

Jquery getting values of slider inside .each loop

I have 3 sliders (they are dynamic, so I need to loop through them).
I have a jsFiddle here: http://jsfiddle.net/mtait/R5czJ/
HTML is:
<label for="slider1">item 1</label>
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0">
<label for="slider2">item 2</label>
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0">
<label for="slider3">item 3</label>
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0">
I am trying to loop through them, and create a JSON string:
function slide() {
var ExtraPrices = [20.00,30.00,50.00];
var ExtraIDs = [1,2,3];
var count = 0;
var arr = [];
$('.mtslide').each(function () {
var obj = {
id: ExtraIDs[count],
price: ExtraPrices[count],
number: $(this).slider("option", "value")
};
arr.push(obj);
count += 1;
});
alert(JSON.stringify(arr));
}
However, "number" or the value of the sliders, is always null:
How do I get the correct value of each slider, within my .each loop above?
thank you,
Mark
jQuery's each function actually gives you two variable: index and Element
http://api.jquery.com/each/
Assuming you want the value of each element you want something like this:
$('.mtslide').each(function (index, Element) {
var obj = {
id: ExtraIDs[index],
price: ExtraPrices[index],
number: $(Element).val()
};
arr.push(obj);
});
Keeping a separate array for price and id can be error prone. You should consider specifying additional values on an html element with data attribute.
http://html5doctor.com/html5-custom-data-attributes/
http://api.jquery.com/data/
Something like this:
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0" data-price="20.00" data-id="1">
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0" data-price="30.00" data-id="2">
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0" data-price="50.00" data-id="3">
Then you can call them more specifically to the element:
$('.mtslide').each(function (index, Element) {
var obj = {
id: $(Element).data("price"),
price: $(Element).data("price"),
number: $(Element).val()
};
arr.push(obj);
});
The complete fiddle:
http://jsfiddle.net/Wwwtv/2/

Fire oninput event with jQuery

I have an oninput event on a textarea to check the height and resize it. Now I need to edit the value sometimes. I do this just by editting the val() in jQuery, but that does not trigger the oninput event. Is there any way to trigger the oninput event programatically with jQuery?
Use .on('input'). For example:
$('textarea').on('input', function() {
text = $('textarea').val();
$('div').html(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea placeholder="Type something here"></textarea>
<div></div>
It is a bit too late, but for future reference, there is the .trigger method.
$("#testArea").on("input", function(e) {
$("#outputArea").text( $(e.target).val() )
});
$("#testArea").val("This is a test");
$("#testArea").trigger("input");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="testArea" type="text" />
<div id="outputArea"></div>
You can simply invoke it, e.g.:
$("input")[0].oninput = function () {
alert("hello");
};
$("input")[0].oninput();
...but as #Sammaye points out, jQuery has no explicit "oninput" handler, so you'll have to use POJS.
Demo on JS Fiddle.
oninput is not actually in JQuery yet.
You can see posts about it here:
http://forum.jquery.com/topic/html5-oninput-event
http://bugs.jquery.com/ticket/9121
Basically the general consensus is that they don't want it yet.
But no, changing val() directly would not trigger the html5 oninput because it's specification states it is when the user, in the UI, changes the value of the input.
Edit:
However some one has kindly made a plugin for people who wish to use HTML5 only events: https://github.com/dodo/jquery-inputevent
You can bind to input and change:
input will be triggered at user input
change will be triggered at change() and to val(" ") assignments, but after some changes
$("#textarea").bind("input change", function() {
alert("change happend");
});
...
after you binded to change you can call it manualy on each val(" ") assignment:
$("#textarea").val("text").change();
or you can overwrite jQuery val(" ") method to trigger change on each user val(" ") call:
(function ($) { var fnVal = $.fn.val;
$.fn.val = function(value) {
if (typeof value == 'undefined') {
return fnVal.call(this);
}
var result = fnVal.call(this, value);
$.fn.change.call(this); // calls change()
return result;
};
})(jQuery);
Try with "keypress" or "keydown".
Example 1:
$("#textarea").keypress(function(){
alert($("#textarea").val());
});
Example 2:
$("#textarea").keydown(function(){
alert($("#textarea").val());
});
push RUN CODE SNIPPET for seeing results
i've been searching for a better example to join an input range to an input value and so
i modified Fernando's example in a JQuery plugin ,so :
for every
<input type="range" min="1" max="100" value="50" id="range1">
you'll have his value:
<input type="text" disabled id="value" class="range1" value="0">
so is like for any parent range id="range1" there is a child id="value" class="range1"
<!-- <script src="../js/jquery.js"></script> -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
1<input type="range" min="1" max="100" value="50" id="range1"><input type="text" disabled id="value" class="range1" value="0"><br>
2<input type="range" min="1" max="100" value="50" id="range2"><input type="text" disabled id="value" class="range2" value="0"><br>
3<input type="range" min="1" max="100" value="50" id="range3"><input type="text" disabled id="value" class="range3" value="0"><br>
4<input type="range" min="1" max="100" value="50" id="range4"><input type="text" disabled id="value" class="range4" value="0"><br>
...<br>
n<input type="range" min="1" max="100" value="50" id="rangen"><input type="text" disabled id="value" class="rangen" value="0"><br>
<script type="text/javascript">
<!--
$(document).ready(function() {
$('input').on("input",function(){
$('input').each(function(index) {
//console.log('1 '+index + ': ' + $(this).text()+',id='+$(this).attr('id'));
if($(this).attr('id')=='value'){
//console.log('2 class='+$(this).attr('class'));
var obj=$('input#'+$(this).attr('class') );
var hisvalue=$(this);
//console.log('3 parent`s value='+obj.val() );
obj.on("input",function(){
hisvalue.val(obj.val());
});
}
});
});
$('input').trigger("input");
});
//-->
</script>

Categories