Passing a js var into jquery action as attribute - javascript

var temp="path.png"
How can I pass temp var into the jquery function as shown below
$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/"+temp />')

Use correct quotes placement in string concatenation:
$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/' + temp + '" />');

$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/' + temp + '" />');

Related

Javascript var in string

So I have this code and would like to know how I could go ahead to put my javascript var into this string. I cannot seem to make a working code for myself.
For the image source i want picture.value to be in there. I have tried different solutions but have not managed to work it out myself. All help is greatly appreciated
var text = "<img src="">
I have currently been trying var text = "<img src=" + picture.value +">
but that doesn't seem to work for me.
You cannot use " & ' this together unless you escape it with a \.
var text = '<img src="' + picture.value + '">'
OR
var text = "<img src=\"" + "Hi" + "\">"
Try using ES6 new feature called Template literals (using quote). It is more cleaner and simpler.
var picture = {'value':'test-src-location'};
var text = `<img src="${ picture.value }">`;
console.log(text);
Assuming your picture.value is not empty.
var text = '<img src=' + picture.value + '>';
Example: https://jsfiddle.net/no293etL/

Building html tag with javascript

The scenario is the following:
I call the buldMyStuff function to build images many times the following way. Wrapping the img into an "a" tag is not an option.
function buildMyStuff(item){
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
return tag;
}
function doClick(type,data){
//do stuff
}
Lets assume that the item.type value is "type" and the item.data value is "data".
The problem with this that when I click the image it says type is not defined. Therefore (and I checked in the built html structure) the img eventually looks like this:
<img src="someimg.png" onclick="doClick(type,data)" />
What I need to achieve is:
<img src="someimg.png" onclick="doClick('type','data')" />
However as I am using the ' character to wrap the whole tag and the " character to wrap the attribute I cannot use anything else. Does someone know the solution for this?
Thank you in advance.
You can use '\' to escape special characters.
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
=>
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
this is invalid;
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
It should be
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
function buildMyStuff(item){
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
return tag;
}

WHy Doesnt This Javascript Function Work

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.

Won't Iterate Over Array In jQuery

So I can get all of the images I want into an array and pass them to $image. However when I try to loop over that array it just keeps alerting the same item 3 times.
The code I'm having trouble with.
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
}
The HTML
<a href="images/slideshow/1-GW.PhillipBarnhart.ReverendMemory.jpg" title="Phillip Barnhart as:
Reverend Memory - a clergyman who stands for decorum and truth." rel="slideshow"><img src="images/view-slideshow.jpg" width="490" height="352" alt="View Slideshow"></a>
<a rel="slideshow" href="images/slideshow/2-GW.BethBrooks.POLLYTODD.jpg">fff</a>
<a rel="slideshow" href="images/slideshow/3-GW.NickHale.NOSTALGIA.jpg">test</a>
The whole script or if you like jsFiddle here is a link. http://jsfiddle.net/h3az4/
var slideShow = {
config : {
wrapper : 'body',
container : 'div',
anchor : 'a[rel="slideshow"]'
},
init : function(config) {
$.extend(slideShow.config, config);
$(slideShow.config.anchor).hide();
$(slideShow.config.wrapper).find(slideShow.config.anchor)
.eq(0)
.show()
.click(function(e){
e.preventDefault();
slideShow.getItem($(slideShow.config.anchor));
});
},
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
},
createTumbnail : function($image){
}
};
$(document).ready(function() {
slideShow.init();
});
Your using the $.each loop wrong.
Your first problem is that $image.attr("x") will get the attr of the first element in the list if $image is a list. What you want is either $($image[i]) or using .get
The second issue is declaring var setup outside the loop. Which means its declared and used once rather then 3 times (since you have 3 items).
$.each($image, function(i){
var setup ='<img src="' + $(this).attr('href') + '" title="' +
$(this).attr('title') + '"/>';
alert( setup);
});
When your using $.each the this object in the function will refer to each object in the array in turn. In this case this is a DOM object so you want to use $(this) to get the jQuery image object.
Look here for a working example http://jsfiddle.net/Raynos/h3az4/3/
I assume $image is an array since you are looping through it. if that's the case, you want something similar to this...
$.each($image, function(i){
var setup ='<img src="' + i.attr('href') + '" title="' + i.attr('title') + '"/>';
alert( setup);
});
check my solution at http://jsfiddle.net/h3az4/5/
allows endless loop of your slideshow, imo you've overcomplicated it a bit and made few conceptual errors as #Dutchie432 pointed
hope this will help as well,
Tom
You can accomplish what you seem to want using map()(docs) .
getItem : function($image){
$image.map( function(i,val){
return $('<img src="' + this.href + '" title="' +this.title + '"/>')[0];
}).appendTo(slideShow.config.wrapper);
},
This will create a new jQuery object that contains the new <img> elements, then will appendTo()(docs) the slideShow.config.wrapper selector.
No need for the intermediate setup variable.
Or maybe a little nicer like this using the properties object argument:
getItem : function($image){
$image.map( function(i,val){
return $('<img>', { src:this.href, title:this.title })[0];
}).appendTo(slideShow.config.wrapper);
},

Escaping quotes in jquery

I'm having a bit of a problem escaping quotes in the following example:
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');
The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:
onkeyup="runFunction(" #row2="" );=""
What exactly am I doing wrong?
Just don't put JavaScript into the HTML string:
$(id).html(
'<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
runFunction("#my" + newId);
});
Thinking about it, in this special case you can exchange the keyup() function body for:
runFunction(this);
because you seem to want to run the function on the object itself.
You need to use HTML character references for HTML attribute values. Try this:
function htmlEncode(str) {
var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');
You forgot to escape the attribute's quotes.
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');
You should use escaped single quotes \' to surround the #my... part.

Categories

Resources