Unable to alert jquery slider value - javascript

I'm writing a code where there are 3 Jquery sliders present, here when I change I want to alert the 3 sliders values.
Here I've 2 problems.
I'm unable to alert the value of the slider that is changed.
I'm unable to know on how I can alert all 3 sliders value.
Here is my code.
$("#a").slider({
range: "min",
orientation: "vertical",
step: 1,
value: 10,
max: 14,
min: 8.5,
create: function (event, ui) {
$("#a").find(".ui-slider-handle").append('<input id="sliderValueA" />')
},
slide: function (event, ui) {
$("#sliderValueA").val(ui.value + "%");
},
change: function (event, ui) {
$(".target-value").text("Hi");
alert($("#sliderValueA").val);
}
});
$("#b").slider({
range: "min",
orientation: "vertical",
value: 0.9,
step: 0.2,
min: 0.4,
max: 1.98,
create: function (event, ui) {
$("#b").find(".ui-slider-handle").append('<input id="sliderValueB" />')
},
slide: function (event, ui) {
$("#sliderValueB").val(ui.value + "g");
},
change: function (event, ui) {
$(".target-value").text("Hi");
alert($("#sliderValueB").val);
}
});
$("#c").slider({
range: "min",
orientation: "vertical",
value: 20,
min: 6,
max: 155,
create: function (event, ui) {
$("#c").find(".ui-slider-handle").append('<input id="sliderValueC" />')
},
slide: function (event, ui) {
$("#sliderValueC").val(ui.value + "%");
},
change: function (event, ui) {
$(".target-value").text("Hi");
alert($("#sliderValueC").val);
}
});
please let me know where am I going wrong and how can I fix this.
Thanks

when I change I want to alert the 3 sliders values.
You can concatenate the value of each slider, and use \n to put each value on a new line within the alert.
Here is the code you need for your alert:
alert('Slider A is: ' + $('#a').slider('value') + '%\nSlider B is: ' + $('#b').slider('value') + 'g\nSlider C is: ' + $('#c').slider('value') + '%');
So your code would look like this:
$("#a").slider({
range: "min",
orientation: "vertical",
step: 1,
value: 10,
max: 14,
min: 8.5,
create: function(event, ui) {
$("#a").find(".ui-slider-handle").append('<input id="sliderValueA" />')
},
slide: function(event, ui) {
$("#sliderValueA").val(ui.value + "%");
},
change: function(event, ui) {
alert('Slider A is: ' + $('#a').slider('value') + '%\nSlider B is: ' + $('#b').slider('value') + 'g\nSlider C is: ' + $('#c').slider('value') + '%');
}
});
$("#b").slider({
range: "min",
orientation: "vertical",
value: 0.9,
step: 0.2,
min: 0.4,
max: 1.98,
create: function(event, ui) {
$("#b").find(".ui-slider-handle").append('<input id="sliderValueB" />')
},
slide: function(event, ui) {
$("#sliderValueB").val(ui.value + "g");
},
change: function(event, ui) {
alert('Slider A is: ' + $('#a').slider('value') + '%\nSlider B is: ' + $('#b').slider('value') + 'g\nSlider C is: ' + $('#c').slider('value') + '%');
}
});
$("#c").slider({
range: "min",
orientation: "vertical",
value: 20,
min: 6,
max: 155,
create: function(event, ui) {
$("#c").find(".ui-slider-handle").append('<input id="sliderValueC" />')
},
slide: function(event, ui) {
$("#sliderValueC").val(ui.value + "%");
},
change: function(event, ui) {
alert('Slider A is: ' + $('#a').slider('value') + '%\nSlider B is: ' + $('#b').slider('value') + 'g\nSlider C is: ' + $('#c').slider('value') + '%');
}
});

Example Solution to get all slider values on change.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Slider - Custom handle</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#custom-handle {
width: 3em;
height: 1.6em;
top: 50%;
margin-top: -.8em;
text-align: center;
line-height: 1.6em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function alertSliderValues() {
var sliderHandle1 = $("#slider1").slider("value");
var sliderHandle2 = $("#slider2").slider("value");
var sliderHandle3 = $("#slider3").slider("value");
alert(
"SliderHandle1=" + sliderHandle1 +
"\nSliderHandle2=" + sliderHandle2 +
"\nSliderHandle3=" + sliderHandle3
);
}
$( function() {
$( "#slider1").slider({
change: function() {
alertSliderValues();
}
});
$( "#slider2").slider({
change: function() {
alertSliderValues();
}
});
$( "#slider3").slider({
change: function() {
alertSliderValues();
}
});
} );
</script>
</head>
<body>
<div id="slider1">
</div>
<br />
<div id="slider2">
</div>
<br />
<div id="slider3">
</div>
<br />
</body>
</html>

According to this documentation http://api.jqueryui.com/slider/#method-value, to get the value of the slider you'd use $( "#slider" ).slider( "value" );
To get for all sliders, if the IDs are known you can just call the "value" attribute just like so
alert($("#a").slider("value") + " " + $("#b").slider("value") + " " + $("#c").slider("value"));
or if they are referenced by a class, you can loop over the array of sliders just like that
var sliderValues = "";
$(".slider").each(() => {
sliderValues += $(this).slider("value") + " ";
});
alert(sliderValues);

I'm unable to alert the value of the slider that is changed.
That happen because you've a typo in your alerts code, .val should be .val() like:
$("#sliderValueC").val();
Instead of:
$("#sliderValueC").val
I'm unable to know on how I can alert all 3 sliders value.
You could create a function that alert the three values and call it instead of alert in every change callback:
function alertValues(){
$(".target-value").text("Hi");
alert( $("#sliderValueA").val() );
alert( $("#sliderValueB").val() );
alert( $("#sliderValueC").val() );
//Or
var a = $("#sliderValueA").val();
var b = $("#sliderValueB").val();
var c = $("#sliderValueC").val();
alert('Slider A :'+ a + ', Slider B :' + b + ', Slider C :' + c);
}
Then call it like :
change: function (event, ui) {
alertValues();
}
//Or
change: alertValues

Related

Values always visible in console.log but sometimes not visible in input fields

I ran into a problem which I am not sure how to fix.
When I drag the knob into the picture a clone is created.
Below the image, a form is then shown with the position of the button.
The problem is that sometimes this value is not updated in this input field.
In line 85 I set that value.
Then on lines 89 and 90 I check if this value is there in the first place.
By means of:
console.log(ui.position.left);
console.log($("#dragItemPositionX[data-id=" + UUID + "]").val());
A value always appears here but when I look at the form I sometimes see no value in the input field.
( As a test case for this, drag a button to the picture a few times. Sometimes you will see no value in the input field.
How is this possible and how can I fix this?
function uuid() {
var dt = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
$(document).ready(function() {
// Create default knob
$('#knob').jqxKnob({
width: 34,
height: 34,
disabled: true,
value: 0,
min: 0,
max: 100,
startAngle: 120,
endAngle: 420,
snapToStep: true,
rotation: 'clockwise',
style: {
stroke: '#000',
strokeWidth: 1,
fill: {
color: '#fff'
}
},
pointer: {
type: 'line',
thickness: 4,
style: {
fill: "#00a4e1",
stroke: "#00a4e1"
},
size: '70%',
offset: '0%'
}
});
//Drag default knob in #droppable div
$(".draggable").draggable({
containment: "#droppable",
appendTo: "#droppable",
helper: "clone"
});
});
// Drag&Drop default knob
$("#droppable").droppable({
drop: function(event, ui) {
//Generate UUID
var UUID = uuid();
// Change class in order to stop the cloning in droppable div.
if (ui.draggable.hasClass("draggable")) {
var $item = $(ui.helper).clone();
$item.removeClass("draggable");
$item.addClass("editable");
$item.attr('data-id', UUID);
$(this).append($item);
$(".editable").draggable({
containment: "#droppable",
appendTo: "#droppable",
drag: function(event, ui) {
$("#dragItemPositionX[data-id=" + UUID + "]").val(ui.position.left);
$("#dragItemPositionY[data-id=" + UUID + "]").val(ui.position.top);
}
});
//Add a form & fill some values
$("#info").append("<form class='pure-form knob' name=" + UUID + " data-id=" + UUID + ">");
$("form[data-id=" + UUID + "]").append($("#template").html());
$("form[data-id=" + UUID + "]").find('input').each(function() {
$('input').attr('data-id', UUID);
$(this).attr('name', $(this).attr('name') + "[]");
});
$("#dragItemPositionX[data-id=" + UUID + "]").val(ui.position.left);
$("#dragItemPositionY[data-id=" + UUID + "]").val(ui.position.top);
console.log(ui.position.left);
console.log($("#dragItemPositionX[data-id=" + UUID + "]").val());
// Show form and active knob
$("form.knob").hide();
$("form[data-id=" + UUID + "]").show();
$("body").find(".active_knob").removeClass("active_knob");
$(".jqx-knob[data-id=" + UUID + "]").find("line").eq(-1).addClass("active_knob");
}
}
})
JSfiddle
Made some minor updates. You had a few items outside of your jQuery block. I suspect that you had some syntax issues.
Test: https://jsfiddle.net/Twisty/acr1dvbf/5/
JavaScript
$(function() {
function uuid() {
var dt = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
// Create default knob
$('#knob').jqxKnob({
width: 34,
height: 34,
disabled: true,
value: 0,
min: 0,
max: 100,
startAngle: 120,
endAngle: 420,
snapToStep: true,
rotation: 'clockwise',
style: {
stroke: '#000',
strokeWidth: 1,
fill: {
color: '#fff'
}
},
pointer: {
type: 'line',
thickness: 4,
style: {
fill: "#00a4e1",
stroke: "#00a4e1"
},
size: '70%',
offset: '0%'
}
});
//Drag default knob in #droppable div
$(".draggable").draggable({
containment: "#droppable",
appendTo: "#droppable",
helper: "clone"
});
// Drag&Drop default knob
$("#droppable").droppable({
drop: function(event, ui) {
//Generate UUID
var UUID = uuid();
// Change class in order to stop the cloning in droppable div.
if (ui.draggable.hasClass("draggable")) {
var $item = $(ui.helper).clone();
$item.toggleClass("draggable editable");
$item.attr('data-id', UUID);
$(this).append($item);
$(".editable").draggable({
containment: "#droppable",
appendTo: "#droppable",
drag: function(event, ui) {
$("#dragItemPositionX[data-id=" + UUID + "]").val(ui.position.left);
$("#dragItemPositionY[data-id=" + UUID + "]").val(ui.position.top);
}
});
//Add a form & fill some values
$("#info").append("<form class='pure-form knob' name=" + UUID + " data-id=" + UUID + ">");
$("form[data-id=" + UUID + "]").append($("#template").html());
$("form[data-id=" + UUID + "]").find('input').each(function(i, el) {
$('input').attr('data-id', UUID);
$(el).attr('name', $(this).attr('name') + "[]");
});
$("#dragItemPositionX[data-id=" + UUID + "]").val(ui.position.left);
$("#dragItemPositionY[data-id=" + UUID + "]").val(ui.position.top);
console.log(ui.position.left);
console.log($("#dragItemPositionX[data-id=" + UUID + "]").val());
// Show form and active knob
$("form.knob").hide();
$("form[data-id=" + UUID + "]").show();
$(".active_knob").removeClass("active_knob");
$(".jqx-knob[data-id=" + UUID + "]").find("line").eq(-1).addClass("active_knob");
}
}
});
});
When I move the clone around, I always get value updates.
Update
If you add more knobs, you will then need to conditionally Add the knob or if it's an existing knob, show the correct form and show the proper position.
Example: https://jsfiddle.net/Twisty/acr1dvbf/95/
JavaScript
$(function() {
function getId() {
var dt = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
function makeKnobDrag(item) {
return $(item).draggable({
containment: "#droppable",
drag: function(event, ui) {
$("#knob-form-" + $(item).data("form") + " .drag-x").val(ui.position.left);
$("#knob-form-" + $(item).data("form") + " .drag-y").val(ui.position.top);
}
});
}
function getActiveKnobPosition() {
return $(".active_knob").closest(".jqx-knob").position();
}
function makeForm(target, uuid) {
var c = $(".active_knob").closest(".jqx-knob").data("form");
var form = $("<form>", {
class: "pure-form knob",
name: uuid,
"data-id": uuid,
id: "knob-form-" + c
}).appendTo(target);
form.append($("#template form").children().clone());
form.find('input').each(function(i, el) {
$(el).attr({
name: $(el).attr("name") + "[]",
"data-id": uuid,
id: $(el).attr("id").substring(0, $(el).attr("id").indexOf("-")) + c
});
});
$("form.knob").hide();
var kPos = getActiveKnobPosition();
$(".drag-x", form).val(kPos.left);
$(".drag-y", form).val(kPos.top);
form.show();
}
// Create default knob
$('#knob').jqxKnob({
width: 34,
height: 34,
disabled: true,
value: 0,
min: 0,
max: 100,
startAngle: 120,
endAngle: 420,
snapToStep: true,
rotation: 'clockwise',
style: {
stroke: '#000',
strokeWidth: 1,
fill: {
color: '#fff'
}
},
pointer: {
type: 'line',
thickness: 4,
style: {
fill: "#00a4e1",
stroke: "#00a4e1"
},
size: '70%',
offset: '0%'
}
});
//Drag default knob in #droppable div
$(".draggable").draggable({
containment: "#droppable",
helper: "clone",
start: function(e, ui) {
ui.helper.addClass("new-item");
}
});
// Drag&Drop default knob
$("#droppable").droppable({
drop: function(event, ui) {
var $self = $(this);
var UUID;
var $item = $(ui.helper).clone();
$(".active_knob").removeClass("active_knob");
if ($item.hasClass("new-item")) {
UUID = getId();
$item.removeClass("new-item").toggleClass("draggable editable ui-draggable ui-draggable-dragging");
$item.attr({
"data-id": UUID,
"data-form": "knob-form-" + ($("form.knob").length + 1)
});
$self.append($item);
$item.find("line").eq(-1).addClass("active_knob");
makeKnobDrag($item, UUID);
makeForm("#info", UUID);
} else {
UUID = $item.data("id");
c = $item.data("form");
$("form.knob").hide();
$item.find("line").eq(-1).addClass("active_knob");
$("#knob-form-" + c).show();
}
}
});
});
As you can see, if it's a new item, it will be added to the droppable. If it's not a new item, it will show the proper form and update the position.

Dynamically change content when slider values are updated

I am trying to dynamically change my page content when the slider values are changed. At the moment the user sets the slider, clicks a button below and content is displayed. When the sliders are changed again, the user has to click the button again to reload the content (because each button is assigned to the goalkeeperstat function.
<a class="chosenstat" title="Saves" value="saves" name="save" onclick="goalkeeperstat(this);">Saves</a>
Rather than having to press the button again I would like the content to change as soon as the user drags the slider handles to their chosen values.
Below is a screenshot of my page.
http://i.imgur.com/eZq08sI.jpg
$(function initSlider() {
$("#slider1").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
slide: function update1 (event, ui) {
$(".amount").val(ui.values[0] + " - " + ui.values[1]);
slidervalueg1 = $('#g1').val(ui.values[0]);
slidervalueg2 = $('#g2').val(ui.values[1]);
}
});
$(".amount").val($("#slider1").slider("values", 0) +
" - " + $("#slider1").slider("values", 1));
});
function goalkeeperstat(element){
$('#result1').empty();
$('.amount').empty();
var category = element.getAttribute("value");
var categoryprompt = element.getAttribute("title");
var infocategory = element.getAttribute("name");
var position = 1;
var fr = $(myjson).filter(function (i,n){return n.element_type===position & n[category] >= slidervalueg1.val() && n[category] <= slidervalueg2.val() });
for (var i=0;i<fr.length;i++)
{
document.getElementById('result1').innerHTML += ("<div class='profile'><img src='https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/110x140/p" + fr[i].code + ".png'/><div class='playerinfo'><p>Name: " + fr[i].first_name + " " + fr[i].second_name + "</p><p>Position: " + posdictionary[fr[i].element_type.toString()] + "</p><p class='teamname'>Team: " + dictionary[fr[i].team.toString()] + "</p><p>" + categoryprompt + ": <span class='categoryprompt'>" + fr[i][category] + "</span></p></div><div class='infobg'><p>Minutes: " + fr[i].minutes + "</p><p>Minutes per " + infocategory + ": " + parseFloat(Math.round((fr[i].minutes / fr[i][category]) * 100) / 100).toFixed(2) + "</p></div></div>");
}
}
EDIT: Tried using "stop" but it wouldn't work. Any other tips?
you can use event or method explicit :
$("#slider1").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
slide: function update1 (event, ui) {
$(".amount").val(ui.values[0] + " - " + ui.values[1]);
slidervalueg1 = $('#g1').val(ui.values[0]);
slidervalueg2 = $('#g2').val(ui.values[1]);
},
stop : function(event, ui){
console.log("slider changed");
// call your fucntion here
}
});

Jquery saying that object doesn't support 'each'

When I run my web app, I get an error saying that "JavaScript runtime error: Object doesn't support property or method 'each'", I'm trying to create a legend below or above my jquery slider...
here is the scripts I'm using
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
and this is my JQuery script
$(function () {
$("#slider-range").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
animate: 'slow',
slide: function (event, ui) {
//$(ui.handle).find('span').html('$' + ui.value);
//
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
}
.each(function() {
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i++) {
var el = $('<label>'+(i+1)+'</label>').css('left',(i/vals*100)+'%');
$( "#slider" ).append(el);
}
})
});
$("#amount").val("$" + $("#slider-range").slider("values", 0) +
" - $" + $("#slider-range").slider("values", 1));
});
Any help would be appreciated.
Thanks
You are applying each on the options object, which only has range, min, max, values and animate. Indeed, no each.
You were calling each() on the slide handler function - misplaced })
$("#slider-range").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
animate: 'slow',
slide: function (event, ui) {
//$(ui.handle).find('span').html('$' + ui.value);
//
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
}// <-- you had it here
}).each(function () {
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i++) {
var el = $('<label>' + (i + 1) + '</label>').css('left', (i / vals * 100) + '%');
$("#slider").append(el);
}
});
You are calling .each() at wrong place you need to do }).each(function () {
$(function () {
$("#slider-range").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
animate: 'slow',
slide: function (event, ui) {
//$(ui.handle).find('span').html('$' + ui.value);
//
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
}
}).each(function () { //you each loop like this
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i++) {
var el = $('<label>' + (i + 1) + '</label>').css('left', (i / vals * 100) + '%');
$("#slider").append(el);
}
})
});

location of moved piece

I am creating a checker variation game.
I am new to jquery but through some help the pieces can now move around the board.
Is there a way to indicate the start location and end location of a move?
I would also like to disable all piece movement once a move has been made.
current code:
$('img').draggable();
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
}
});
jsfiddle http://jsfiddle.net/blueberrymuffin/bLb3H/
thanks.
$('img').draggable({
start: function(e, ui) {
alert('Starting move from position (' + ui.position.top + ', ' + ui.position.left + ')');
},
stop: function(e, ui) {
alert('Ending move at position (' + ui.position.top + ', ' + ui.position.left + ')');
}
});
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
$('img').draggable('disable');
}
});​
I think I figured it out.
Here is the code:
$('img').draggable({
start: function(e, ui) {
var myCol = $(this).closest("td").index() + 1;
var myRow = $(this).closest("tr").index() + 1;
$('#coords').html('Row ' + myRow + ', Col ' + myCol);
},
});
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
$('img').draggable('disable');
}
});
and the jsfiddle: http://jsfiddle.net/bLb3H/5/
I am not sure though how to replace the current image with the new one that was dragged onto it (currently both images occupy the same cell). Any ideas?
Thanks.

How to replace a div content with other div using jquery or Javascript?

Hi all i am having some which i am appending to a div dynamically in my view....i have three ajax calls for different methods....firstly i show all the images of product in a div ....and if a user selects the price range the proucts will be displayed of that price range only and same for colours..what i want is i want this when user selects price range or color the div with all images should be replaced with the new images how can i do this can any one help me here
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductLayout", function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
scrollablediv();
});
});
function scrollablediv() {
$("div#makeMeScrollable").smoothDivScroll({
mousewheelScrolling: true,
manualContinuousScrolling: true,
visibleHotSpotBackgrounds: "always",
autoScrollingMode: "onstart"
});
}
</script>
<script type="text/javascript">
$(function () {
$("#slider-range").slider({
range: true,
min: 0,
max: 500,
values: [0,0],
slide: function (event, ui) {
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
},
change: function (event, ui) {
// when the user change the slider
},
stop: function (event, ui) {
// when the user stopped changing the slider
$.get("/api/ProductLayout", { firstPrice: ui.values[0], secondPrice: ui.values[1] }, function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
});
$("#amount").val("$" + $("#slider-range").slider("values", 0) +
" - $" + $("#slider-range").slider("values", 1));
});
</script>
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
</script>
and this is my html
<div id="makeMeScrollable" style="height: 400px; width: 400px;">
</div>
i should append all the images only to the above div replacing the previous images
As said by jaswant you can use .empty() method but not .empty().append() what this does is it will empty the data when ever an new record is binded so use .empty() method before your ajax call or json call
$("#makeMeScrollable").empty();
add the above line before your ajax call
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$("#makeMeScrollable").empty();
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
Try this,
$("#makeMeScrollable").html('ProdcutID<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' +
ele.Price + '</span><img src="' + ele.ImageURL + '" />');
You can always use html() in place of append() to remove the existing content.
or you can do empty the element before append with .empty().append()
EDIT (after comments)
var $div = $("#makeMeScrollable");
$div.empty();
$.each(data, function (idx, ele) {.append('ProdcutID' + '<span>' + ele.ProductID + '</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({
src: ele.ImageURL
}).appendTo("#makeMeScrollable");
});
You should do the empty as the first action in your success handler. Because the calls are asynchroneous, you will have the risk of products interfering with each other if you clear the area before you do the ajax call.
$(document).ready(function () {
$.getJSON("/api/ProductLayout").success(function (data) {
clearProductDisplayArea();
displayProductInfo(data);
scrollablediv();
});
});
function clearProductDisplayArea(){
$("#makeMeScrollable").empty();
}
function displayProductInfo(data){
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
}

Categories

Resources