<img> src attribute not changing using Jquery - javascript

Hi guys I have made a JqueryUI simple slider,on certain value range I make Image URL and then try to change src attribute.
There are four images I'm trying to change.
Check the jsFiddle here.
I think the code is fine but its not working ,I dont know why ?

Replace this:
$("#" + postRetrmntImage).attr('src', ImageName );
to this:
$("#postRetrmntImage").attr('src', ImageName );
The problem is that youre not assigned any postRetrmntImage variable.
See update jsFiddle demo

demo http://jsfiddle.net/8Sw5J/
Explanation: Please use this: $("#" + sliderId).prop('src', ImageName ); since in your function you are passing the id as sliderId.
Also If I may suggest use .prop good read here: .prop() vs .attr()
Rest demo you can see how it works,
Hope this helps :)
full code
$(document).ready(function () {
makeSingleSliderWithImage('postRetrmntMnthlyPaymt', 0, 10000, 0, 500);
}
);
function makeSingleSliderWithImage(sliderId, minimum, maximum, val, steps) {
//Display label shud have a X appended
$('#' + sliderId).slider(
{
//range: 'min',
min: minimum,
max: maximum,
step: steps,
//starting values for silders
value: val,
slide: function (event, ui) {
//var ImageURL = "Images/";
//var ImageName = "";
//var ext = ".jpg";
if ((ui.value >= 0) && (ui.value <= 2000))//Basic: 0-2000
ImageName = "http://www.iconempire.com/icon-processor/icon40.gif";
else if ((ui.value >= 2500) && (ui.value <= 4500))//Moderate: 2500-4500
ImageName = "http://aux.iconpedia.net/uploads/14234829766434728.png";
else if ((ui.value >= 5000) && (ui.value <= 7000))//Comfortable: 5000-7000
ImageName = "http://www.iconempire.com/icon-processor/icon40.gif";
else if ((ui.value >= 7500) && (ui.value <= 10000))//Luxury:7500-10,000
ImageName = "Luxury";
//var fullURL = ImageURL + ImageName + ext;
//change Image URL
$("#" + sliderId).prop('src', ImageName ); //{ src: fullURL });
alert($("#" + sliderId).prop('src'));
//change Slider Value
$("#" + sliderId + "X").text(ui.value);
}
}
);
}​

Trying doing this:
$("#" + postRetrmntImage.toString()).attr('src', ImageName );

Change line...
$("#" + postRetrmntImage).attr('src', ImageName );
to...
$("#postRetrmntImage").attr('src', ImageName );

assign a value to postRetrmntImage then use prop instead of attr see why prop
var postRetrmntImage="postRetrmntImage";
$("#" + postRetrmntImage).prop('src', ImageName );

Try this
$("#postRetrmntImage").attr('src', 'newimage.png');

Related

Can't set value of JQuery UI Slider

I have 3 Sliders in one JQuery Dialog, i want them to have a maximum value, but the maximum is not only for one slider it is for the sum of all of them. My script runs fine in google chrome debuger the only problem is that the value of the slider is not updated in $(this).slider("value", (sliderMax - sum));
$(".slider").each(function() {
var id = $(this).attr("id");
id = id.replace("Slider", "Value");
var sliderMax = 27;
$(this).slider({
range : "min",
min : 0,
max : sliderMax,
value : $("#" + id).attr("value"),
slide : function(event, ui) {
var sum = 0;
$(".sliderValue").each(function() {
if ($(this).attr("id") != id) {
sum += parseInt($(this).attr("value"));
}
});
if ((sum + $(this).slider("value")) > sliderMax){
$(this).slider("value", (sliderMax - sum));
}
$("#" + id).val(ui.value);
}
});
});
pls help me.
Ok finaly i found the solution:
if ((sum + ui.value) > sliderMax){
return false;
}
It is because of params of parseInt and value:... parseInt returns fake value when the string provided as parameter doesn't contain a number! please define the value variable outside the options as follows
$(".slider").each(function() {
var id = $(this).attr("id");
id = id.replace("Slider", "Value");
var sliderMax = 27;
var _value=$("#" + id).attr("value");
$(this).slider({
range : "min",
min : 0,
max : sliderMax,
value :value,
slide : function(event, ui) {
var sum = 0;
$(".sliderValue").each(function() {
if ($(this).attr("id") != id) {
var valueString=$(this).attr("value");
sum += parseInt(valueString);
}
});
if ((sum + $(this).slider("value")) > sliderMax){
$(this).slider("value", (sliderMax - sum));
}
$("#" + id).val(ui.value);
}
});
});
EDITS:
copied your solution to help readers
if ((sum + ui.value) > sliderMax){
return false;
}

how do I cycle through background images by clicking a button?

I want to preview some backgrounds by using a button to cycle through them, just not very good at the js. I have them named "1"-"13". I wanted to step through them. When I get to "13" I want it to set it back to "1" when "next" is clicked and when "prev" is clicked when it gets to "1" to set it to "13". This is what I've tried but I know my syntax is wrong for the js.
HTML
<button id="n" class="b">NEXT</button>
<button id="p" class="b">PREV</button>
CSS
body {
background:black;
}
.b {
background:black;
color:white;
}
JS
$(document).ready(function(){
var i = 1;
$("#n").click(function() {
alert(i);
i++;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===14){i=1;};
});
$("#p").click(function() {
alert(i);
i--;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===0){i=13;};
});
});
Still working on it but some help would be nice getting it done faster.
http://jsfiddle.net/80nz56wy/ I guess a jsfiddle won't help much if I'm using local content.
You should also try this. Here conditions are written before setting CSS, which will check first and then assign the image path.
$(document).ready(function() {
var i = 0;
$("#n").click(function() {
i++;
if (i > 13){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 13){ i = 1; };
});
$("#p").click(function() {
i--;
if (i <= 0) { i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 1) { i = 13; };
});
});
Other wise you may get wrong image paths, something like:
images/bg/0.png
or
images/bg/-1.png
Change Your javascript coding as below..
var i = 1;
$("#n").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i+1;
if (i==13){i=1};
});
$("#p").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i-1;
if (i==1){i=13};
});
Here it is, not sure what I changed the 20 times I edited the same line over and over but I must have gone full retard earlier.
$(document).ready(function(){
var i = 0;
$("#n").click(function() {
i++;
if ( i > 13 ){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
$("#p").click(function() {
i--;
if ( i <= 0 ){ i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
});

jQuery bug when using bounce effect

I have problem with jQuery bounce effect. Every thing works good when there is no bounce - with bounce, when You move very fast many times on button - in sometime, box just doesn't hide. What is wrong in this jsfiddle?
My jsfiddle:
http://jsfiddle.net/d6mSA/170/
My JS:
$('.flex_section').delegate('a','mouseenter mouseleave',function(e){
var a = $(this).attr('id');
if (e.type == 'mouseenter'){
clearTimeout(t_on)
if (a == 'abc'){
clearTimeout(t_off)
t_on = setTimeout(function() { popup_show(a,t_on); }, 10);
}
} else {
t_off = setTimeout(function() { popup_remove(a,t_off); }, 1000);
}
)}
function popup_show(type,string){
if (type == 'abc'){
$('#pc_' + type).css('display','block');
$('#pc_' + type).effect( "bounce",{times:3,distance:20},1000);
}
clearTimeout(string);
}
function popup_remove(type,string){
$('#pc_' + type).css('display','none');
clearTimeout(string)
}
Keep it simple:
function popup(){
$('.flex_top a').hover(function(){
var type = $(this).attr('id');
var offset = $('#' + type).offset();
$('#id_' + type).css('display','block')
.offset({left:offset.left + 100, top:offset.top + 380})
.effect( "bounce",{times:3,distance:20},1000);
},function(){
var type = $(this).attr('id');
$('#id_' + type).fadeOut();
}
);
}
And dont call many times the same object search $('#id_' + type)
Try using stop
$('#pc_' + type).stop().effect( "bounce",{times:3,distance:20},1000);

How can I change to a default background image

I use the following function to create dynamic elements using an ajax response.
function itemGroupSelection(elem,majorGroupId,itemGroupId){
var itemGroup;
var majorGroup;
if(elem == undefined || elem == null || elem == ""){
var itemGroup = itemGroupId;
var majorGroup = majorGroupId;
}else if(majorGroupId == null && itemGroupId == null){
var itemGroup = elem.attr("id");
var majorGroup = elem.attr("majorgroup");
}
$('.breadcrumb a').removeClass('active');
if(elem == ""){
$('.breadcrumb a').first().addClass('active');
}else{
elem.addClass('active');
}
var selectedOutlet = $('#outlets select').children(":selected").attr("id");
$('.item').show();
$('.breadcrumb').show('1');
var data = "majorGroupId=" + majorGroup + "&itemGroupId=" + itemGroup + "&outletCode=" + selectedOutlet;
if(selectedOutlet == undefined){
getSystemMessage('Please select an outlet.');
}else{
ajaxCall("/getItems","POST",data,function(result){
var element = $('#model-item').find('.item').first();
$('#item-list-section').empty();
for(var i = 0; i < result.items.length; i++){
var clone = element.clone();
clone.attr("id", result.items[i].itemId);
clone.find('.item-price').html("<h4>" + result.items[i].rate.toFixed(2) + "</h4>");
if(result.items[i].itemName.length >= 20){
clone.find('.item-name').css('overflow','hidden');
clone.attr('title', result.items[i].itemName )
}
clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>");
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
clone.draggable({
revert : false,
zIndex: 1,
containment: "window",
opacity: 0.5,
cursor: "move",
helper: function() { return $(this).clone().appendTo('body').show(); }
});
$('#item-list-section').append(clone);
}
});
}
}
Using the following command I try to select the background image in the local disc.
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
How can i switch to a default image if there is no image in the path defined. I'm using jQuery 1.9.
Try using the onerror attribute of img, if the link given in src attribute fails to load, ur function in error is called and u can set your default image there (w3schools.com/jsref/event_img_onerror.asp)
You need to handle the onerror event of this image, which will occur whenever the file cannot be found:
$('#image').error(function(){
$(this).off('error'); // otherwise, inexistence of the default image is a real pain
$(this).attr('src', 'http://www.google.ca/images/srpr/logo4w.png');
});
Take a look at this working FIDDLE.
Then,
in your situation, you could have something like this:
var path='the path';
clone.css('background-image', 'url('+path+')');
$('<img src="'+path+'" />').error(function(){
$(this).off('error');
clone.css('background-image', 'url('+default_path+')');
});
Hope this helps :-)

How to add an attribute and remove the attribute with an onchange event?

I have multiple selects and would like to add or remove a name attribute depending on the option that is chosen in the first select.
Here is a fiddle for an example:
http://jsfiddle.net/Nirvanachain/DZFFe/
You just had a few things backwards and you forgot the '.' in the class selector: $('.class'). I fixed the fiddle: http://jsfiddle.net/DZFFe/7/
$("#mySelect").change(function() {
$(".selectorClass").removeAttr("name");
var x = document.getElementById("mySelect").value;
if($("#" + x)) {
$("#" + x).attr("name", "myName");
}
});
​
This should work:
$("#mySelect").change(function() {
var x = $(this).val();
if ($("#" + x).length > 0) {
$("#" + x).attr("name", "myName");
} else {
$(".selectorClass").removeAttr("name");
}
});​
Something like the following?
$("#mySelect").change(function() {
$('.selectorClass').removeAttr('name');
$('#' + $(this).val()).attr('name', 'myName');
});
​
http://jsfiddle.net/DZFFe/8/
there were problems when !!x === false (ex: empty string in this case). I added a simple check on the if
I also added a missing . to select by class
$("#mySelect").change(function() {
var x = document.getElementById("mySelect").value;
if(x && $("#" + x)) { //added to check if x != ""
$("#" + x).attr("name", "myName");
} else {
$(".selectorClass").removeAttr("name"); //added missing "." to actually select classes
}
});
Here is a jsFiddle

Categories