html
<h1>HTML Slider Test</h1>
<div class="slider" data-max="100"></div>
<p>Your slider has a value of <span class="slider-value"></span></p>
<input type="button" value="send" class="send">
<div class="slider" data-max="400"></div>
<p>Your slider has a value of <span class="slider-value"></span></p>
<input type="button" value="send" class="send">
jQuery
var a = 0;
$(".slider").each(function() {
$(this).slider({
value : 5,
min : 1,
max : $(this).data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$(this).next().find('span.slider-value').html(ui.value);
}
});
});
$(".send").click(function () {
var c=$(".slider-value").text();
alert(c);
});
on clicking first button i want value of that alone..but i am getting the value of both sliders.
http://jsfiddle.net/5TTm4/1906/
$(".slider-value") is returning both fields. Use Refiners to get a specific one.
Example:
$(".slider-value").first()
$(".slider-value").last()
http://jsfiddle.net/5TTm4/1909/
Dynamic solution
Simply create the button and its click event on the fly (or attach to an inline button) when creating the slider.
var a = 0;
$(".slider").each(function() {
var slider = this;
$(slider).slider({
value : 5,
min : 1,
max : $(this).data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$(this).next().find('span.slider-value').html(ui.value);
}
});
var button = $('<button>send</button>');
$(button).click(function() {
alert( $(slider).slider("option", "value"));
});
$(slider).next().find('span.slider-value').after($("<br />"), button);
});
Demo
You need a way of identifying the slider value you want to take, which currently wasn't possible without hardcoding it: .prev().prev().find(...blabla), which is a bad way of doing it, since your structure might change.
I updated your jsfiddle to make it work and give an example of how to easily do this using a data attribute and an ID: http://jsfiddle.net/5TTm4/1908/
You basicly give the button a selector of what element it is 'bound' to: data-slider="#slider-value-2"
You also give the slider value an id that matches that selector: id="slider-value-2"
Modify the onClick function:
var $this = $(this);
var c=$($this.attr('data-slider')).text();
Now you have a flexible way of retrieving values and binding elements to the buttons without being dependent on the dom. I suggest using the same technique for binding the value elements to the slider itself.
While i'm at it: cache the value of $(this), it's faster and saves you a lot of scoping issues if you expand your code.
$(".slider").each(function() {
var $this = $(this);
$this.slider({
value : 5,
min : 1,
max : $this.data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$this.next().find('span.slider-value').html(ui.value);
}
});
});
Related
I am using a HTML range slider to zoom in and zoom out an image. I also want to show two buttons with slider like + for zoom and − for zoom out. When a user clicks on either of these buttons, the slider should also be moved. But I am unable to do this. Here is my code.
<div id="slider">
<input id="slide" type="range" min="330" max="1200" step="30" value="330" onchange="ImageViewer.sliderAction(this.value)" />
</div>
Here is my function:
var sliderAction = function (value) {
$sliderChosen.html(value);
$("#img").width(value);
$("#img").height(value);
};
When I click the button, I tried this:
btnZoomIn.click(function() {
$("#slide").value(); //Want to change value but value is undefined.
});
Is there any way to change slider value and move it as well on button click?
use val()
btnZoomIn.click(function() {
//if value < max
$("#slide").val(parseInt($("#slide").val())+30);
$("#slide").trigger('change');
});
https://jsfiddle.net/9jfst447/
You can use callback function of .val() and then trigger onchange event:
var sliderelement = $( "#slide" );
btnZoomIn.click(function() {
sliderelement.val(function( index, value ) {
return parseInt(value,10) + 30;
});
sliderelement[0].onchange()
});
I have this working script. It simply loop through and Object and display
the object key in HTML as sliding bar.
jQuery(function($) {
$('#threshold').change(updateThreshold);
function updateThreshold () {
var thresholdIndex = parseInt($('#threshold').val(), 10);
$("#foldchange_threshold").html(foldchange_thresholds[thresholdIndex]);
};
var foldchange_thresholds = [];
var mydata = {"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] };
Object.keys(mydata).sort().forEach(function(key) {
foldchange_thresholds.push(key);
});
$('#threshold').attr('max', foldchange_thresholds.length-1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<body>
<!-- Display the sliding bar -->
<input id="threshold" type="range" min="0" max="1" step="1" value="0" />
<br>
<!-- Show foldchange threshold -->
<div id="foldchange_threshold" style="display: inline-block; align:center;"></div>
</body>
</html>
What I want to do, as user move the sliding bar, I'd like to get the element.
I am looking at something like these lines. But not sure where to put it.
var userFCchoice = document.getElementsByName('foldchange_threshold');
console.log(userFCchoice);
So if user slide to the value 3 the console log should print it out. How can I go about it?
No need for external plugins for this, jQuery is enough - You can attach your own mousedown, mousemove,mouseup combination to read the range input while dragging around:
JSnippet DEMO - Input range live update while dragging
$(function() {
//Global variable that holds the value and updates while dragging.
var valueTemp = 0;
//Events functions:
var changeEvent = function(){
var thresholdIndex = parseInt($('#threshold').val(), 10);
$("#foldchange_threshold").html($(this).val());
};
var downEvent = function(){
$(this).bind('mousemove',moveEvent);
};
var moveEvent = function(){
//trigger the change or comment it and do what ever you want:
$(this).trigger('change');
//Store the value into a variable available by other functions as asked in the comments:
valueTemp = $(this).val();
console.log($(this).val());
};
var upEvent = function(){
$(this).unbind('mousemove');
};
//Bind events - mousemove is bind and unbind by the mousedown & mouseup events.
$('#threshold').change(changeEvent);
$('#threshold').mousedown(downEvent);
$('#threshold').mouseup(upEvent);
});
EDIT:
Afetr some comments here is an update with the working example that saves the value to a "global" variable while dragging:
JSnippet DEMO update - Input range live update while dragging update
Have you tried using .slider functionality?
I've made a little example of getting the value to console.log, in the example below I'm using the jquery-ui.min.js and jquery-ui.css so that you can use the .slider.
slide: -
This section will show the value as 3 in the console.log
change: - This section will show the value in foldchange_threshold as 3.5
storedElementValue - I've create this as a global variable to store the value of the ui.value for later use.
.css() - You can add the .css() to quickly add values of how you want to style the element or you could also use .addClass() to add a class to the slider and then you change the style in your css style sheet
// Global variable to store value of the slider element
var storedElementValue = 0;
$(function($) {
var foldchange_thresholds = [];
var mydata = {
"3": ["c", "d"],
"3.5": ["j", "k"],
"1.5": ["a", "b"],
"2.5": ["x", "y"]
};
Object.keys(mydata).sort().forEach(function(key) {
foldchange_thresholds.push(key);
});
$("#threshold").slider({
min: 0, // min value
max: foldchange_thresholds.length - 1, // max value
step: 1,
value: 0, // default value of slider
slide: function(e, ui) {
// Show console log of element value
console.log(ui.value);
storedElementValue = ui.value;
},
change: function(e, ui) {
var thresholdIndex = parseInt(ui.value, 10);
$("#foldchange_threshold").html(foldchange_thresholds[thresholdIndex]);
$("#foldchange_threshold_storedValue").html("Stored value for later use: " + storedElementValue);
}
}).css("width", "200px");
});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<!doctype html>
<html>
<body>
<!-- Display the sliding bar -->
<div id="threshold"></div>
<br>
<!-- Show foldchange threshold -->
<div id="foldchange_threshold" style="display: inline-block; align:center;"></div>
<br>
<div id="foldchange_threshold_storedValue" style="display: inline-block; align:center;"></div>
</body>
</html>
I am trying to use html input fields to control a sketch. Now I want to make a loop to generate more then one input.
var uivars = {
tA: "40", // set initial values
tB: "10",
};
Then I refer to those variables in the sketch:
<script type="application/processing" data-processing-target="pjs">
void draw() {
background(255);
var a = uivars.tA;
var b = uivars.tB;
line(0,b,a,b);
}
</script>
Then I get the values from the input fields and update the uivar variable in the beginning:
<script type="text/javascript" >
$(document).ready(function(){
$("#word_textboxA").keyup(function () { // whenever text is entered into input box...
uivars.tA = $(this).val(); // update word variable,
});
$("#word_textboxB").keyup(function () { // whenever text is entered into input box...
uivars.tB = $(this).val();
});
$("#word_textboxA").val(uivars.tA); // initialize input textbox contents.
$("#word_textboxB").val(uivars.tB); // initialize input textbox contents.
});
</script>
And the inputs:
<div id="PVarray">
<input type="text" id="word_textboxA"/><br/>
<input type="text" id="word_textboxB"/>
<div/>
I am building a sketch using processing js and will have over 40 inputs. So I am looking for a way to make a loop for these steps.
No I've managed to generate a number of input fields putting this somewhere:
<!-- <script>
window.onload = initAll;
function initAll(){
for(var i = 0; i<=1; i++)
{
var c=document.getElementById('PVarray');
var input = document.createElement('input');
input.setAttribute('type','text');
input.setAttribute('size','1');
input.setAttribute('id','num'+(i+1));
input.setAttribute('value', 'id' );
//Adds first input to container
c.appendChild(input);
input = '';
}
document.getElementById("show").innerHTML = uivars.tA;
}
</script> -->
But I just cannot find a way to refer in the jquery part to the changing id's of the html inputs.
I am not a experienced programmer. I looked around to find the answer but this is just a difficult one for me. My sketch will need over 40 inputs. the loop should just generate the html inputs, set the initial variables, update the variables on inputchange and give the values to the sketch. The names of the inputs and initial values can be put in a array.
If I understand correctly, the solution is quite simple.
You tagged the question with "jQuery", so here is a jQuery solution.
$(document).ready(function () {
//This is the keyup event handler, attached below to all <input> elements
function updateUivars() {
uivars[this.id] = this.value;
}
//a jQuery-wrapped reference to the PVarray container
var $c = $('#PVarray');
//Loop through uivars properties to create <input> elements with :
// - id equal to the property (the key)
// - an initial value equal to uivars[key]
$.each(uivars, function(key, value) {
$('<input type="text" size="1" />').attr('id', key).val(value).appendTo($c).on('keyup', updateUivars);
});
});
EDIT
So now, for each univars property, there is one value and two pieces of associated text.
var uivars = {
Ins: [30, "Insulation", "kWh/m2/day"],
D: [40, "Deterioration", "%"],
AO: [10, "Azimuth Offset", "%"],
SD: [20, "Surface Deposits", "%"],
TC: [30, "Temperature", "DegC"]
};
The loop that creates the input elements clearly needs to be amended to cause the associated text to be displayed.
Maybe it is less clear that the keyup event handler also needs to be modified to store values back in element [0] of the appropriate array.
Something like this should do it :
$(document).ready(function () {
//This is the keyup event handler, attached below to all <input> elements
function updateUivars() {
uivars[this.id][0] = this.value;
}
//a jQuery-wrapped reference to the PVarray container
var $c = $('#PVarray');
//Loop through uivars properties to create an inner div containing:
// - a label for the property's name
// - an <input> elements with :
// * id equal to the property (the key)
// * an initial value equal to uivars[key][0]
// - a label for the property's units
$.each(uivars, function(key, arr) {
var $div = $('<div class="property"/>').appendTo($c);//inner block element
$('<label/>').text(arr[1]).appendTo($div);
$('<input type="text" size="3" />').attr('id', key).val(arr[0]).appendTo($div).on('keyup', updateUivars);
$('<label/>').text(arr[2]).appendTo($div);
});
});
If desired, the inner divs can be styled in CSS with a .property {...} directive.
I've got a jQuery UI slider. When the user uses a slider, the slider updates an attr variable in the div tag of the slider
$(".slider").each(function() {
var value = parseInt($(this).attr('data-init-value'), 10);
var amin = parseInt($(this).attr('data-min'), 10);
var amax = parseInt($(this).attr('data-max'), 10);
console.log(value, " ", amin, " ", amax)
$(this).empty().slider({
value : value,
min : amin,
max : amax,
range : "min",
animate : true,
slide : function(event, ui) {
$(this).attr('data-value', ui.value);
}
});
});
The example div tag in the html:
<div class="slider" data-min="200" data-max="600" data-init-value="300" data-bind="attr: { 'data-value': someValue }"></div>
When the slider is changed the data-value is updated in the <div> but the js variable doesn't change. (in other, trivial binding cases - like text: - it works.)
How to bind this action?
I suggest you do this the other way around. Bind the value of the slider to an observable property on your viewmodel, and then bind the attribute to that observable.
Then you can always access the most recent value of the slider directly through the viewmodel, and the UI will stay up to date as well.
And further, if you want to subscribe to the update event of that observable, you can bind to that as well. Here is an example from the documentation:
myViewModel.personName.subscribe(function(newValue) {
alert("The person's new name is " + newValue);
});
And finally, this might as well be a possible duplicate of: Identify the attribute change event in KnockoutJS?
-- Update to answer comments
Given the following viewmodel:
var viewModel = {
mySliderValue: ko.observable(0)
};
Then, in your slider callback, you could do something like this:
viewModel.mySliderValue(value);
And then, in your view, having the following attr binding:
data-bind="attr: { 'data-value': mySliderValue }"
... will cause the UI to update when the observable changes its value.
PS. I suggest you no longer delete this thread since my answer is starting to deviate more and more from the one I linked to.
The way to do it is to register an event handler.
o.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
JSFiddle for full example:
http://jsfiddle.net/snLk8/3/
$(function(){
$('.tab2').live('click', function() {
$('#coverTextH3').text(data[1].H3)
$('#coverTextP').text(data[1].P)
});
});
Lets say I have a link How do I pass data, the index of an array, to a jQuery function so I do not have to repeat my code, for each index [0]-[7]?
var data = [
{
H3: 'name',
p: 'more'
},
{
H3: 'string',
p: 'more strings'
}]
There are numerous options. If attaching handlers via javascript, I would select basing on element's id or some custom attribute, not the class. So say you have a number of links like this:
Tab 1
Tab 2
Tab 3
javascript in this case would be
$(function(){
$('a[link-number]').live('click', function() {
var index = $(this).attr('link-number') * 1 - 1;
$('#coverTextH3').text(data[index].H3)
$('#coverTextP').text(data[index].P)
});
});
Alternatively, you can attach click handlers right in your a elements declaration:
Tab 1
Tab 1
Tab 1
and define setCover function like this:
function setCover(index) {
$('#coverTextH3').text(data[index].H3)
$('#coverTextP').text(data[index].P)
}
Each of alternatives require changes in your htlm. If for some reason it is not possible, you need to at least now the range of your tabs, which can be quite tricky.
Something similar to this should work:
markup:
<a href="www.link.com" data-index="1" id="link1" />
javascript:
$(function(){
$('#link1').live('click', function() {
var idx = $(this).data('index');
$('#coverTextH3').text(data[idx].H3)
$('#coverTextP').text(data[idx].P)
});
});
if your link IDs correspond to the index order in the array you can do something like this:
example jsfiddle
jQuery:
$(function() {
$('.tab2').live('click', function(e) {
e.preventDefault();
// parse the integer from the ID
// and get the 0-based index (by subtracting 1)
var idx = $(this).attr('id').replace('link', '') * 1 - 1;
$('#coverTextH3').text(data[idx].H3)
$('#coverTextP').text(data[idx].p)
});
});
HTML:
Link 1
Link 2
<h3 id="coverTextH3"></h3>
<p id="coverTextP"></p>
Text
I'm not sure I understand exactly what you're asking. If this doens't fit, please clarify.