Trying to covert a variable into its value within a URL - javascript

I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?

Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()

You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");

JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);

A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.

Related

jQuery append with variable as src

Just learning jQuery and cannot get my variable into src when I use append. It either doesn't work at all, or I just get the string representation of my variable name when I look in the console.
This is my offending code:
var $googleURL = "http://maps.googleapis.com/maps/api/streetview?size=600x300&location="+$googleStreet+","+$googleCity;
$($body).append('<img src='$googleURL'></img>');
I don't want to use attr because there is no img tag on the page, just a body tag. Where did I go astray?
please try
$($body).append("<img src='"+ $googleURL + "'></img>");
With Javascript, you can put variables inside strings using +
Like this: "string, " + variable + ", more string"
Try this code, it may work depending on what you're trying to accomplish.
var googleURL = 'http://maps.googleapis.com/maps/api/streetview?size=600x300&location='+googleStreet+','+googleCity;
$($body).append('<img src="' + googleURL + '"></img>');

Use indexOf to detect if the value has comma

I'm trying to use the indexOf property in JavaScript/jQuery to detect if there's a comma in a value. This is what I'm trying:
var valueTotalCost = data.TotalCost;
if (valueTotalCost.indexOf('.') > -1)
{ $('table#cartTable tr#' + data.AppItemId + ' td:nth-child(3)').text('£' + data.TotalCost); }
else
{ $('table#cartTable tr#' + data.AppItemId + ' td:nth-child(3)').text('£' + data.TotalCost + '.00'); }
I'm getting an error
valueTotalCost.indexOf is not a function
What might I be doing wrong and how I can fix this? I want to detect if the value already has decimals then don't put tow trailing decimal places, otherwise put two decimal places.
Change the first line from
var valueTotalCost = data.TotalCost;
to
var valueTotalCost = data.TotalCost.toString();
The reason that you're having this problem is most likely because you are trying to use .indexOf() on a number of some kind. .indexOf() is a string method, and so it isn't accessible on numbers.
Usually when you run into a problem like this, I would recommend hopping on Google and searching for the method name. Then you can hit up a Mozilla Resource (generally the easiest to read in my opinion.) like this one:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
Try
var valueTotalCost = String(data.TotalCost);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Javascript & problems

I have the following code:
var artist = document.getElementById("txtBoxArtist").value;
When value is plain text, e.g. Biffy Clyro, artist = Biffy Clyro
When value contains &, e.g. Mumford & Sons, artist = Mumford
I the send artist value using AJAX, and recover the value on another php page like this:
var data = "nameTitle=" + title + "&nameArtist=" + artist;
[...]
$nameArtist=$_POST['nameArtist'];
Why does this happen and how to avoid it? It is giving me lots of problems this &symbol...
Thank you all!
You need to encode the values before sticking them on the URL.
var data = "nameTitle=" + encodeURIComponent(title) + "&nameArtist=" + encodeURIComponent(artist);
You should also see this.
Some characters are special and need 'escaping' to encode their values - as you are showing using & instead of &.
However, these escaping principles are different for HTML content and for URLs/URIs.
In URI, & is escaped as %26 and not as & - so you should either use that or the appropriate encoding/decoding functions, not the HTML entity encoding/decoding.
I guess you can encode valiables before sending them like this:
artist = encodeURIComponent(artist);
title = encodeURIComponent(title);
var data = "nameTitle=" + title + "&nameArtist=" + artist;
hope this helps.

How to "Quote" a String in jQuery?

Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.

HTML5 data being read as a number instead of a string?

I have the following HTML:
<tr id="row_1" data-rk="02000008" data-pk="0001I">
When I check this with firebug it shows as:
dataset DOMStringMap { rk="02000008", pk="0001I"}
pk "0001I"
rk "02000008"
I then use jQuery to read this:
var pk = $("tr[id='row_" + row + "']").data('pk')
var rk = $("tr[id='row_" + row + "']").data('rk')
However this is what the firebug debuggers shows when I check the values in my javascript. They are also the same values that are later sent to my C# code in an Ajax call.
pk shows as "0001I"
rk shows as 2000008
Can someone explain this? Both rk and pk are coded in the same way, both have one or more leading zeros but the one returns as a string and the other as a number.
Javascript autoparses so the trailing 'I' in "0001I" causes javascript to interpret it as a string
This is by design:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
What you have to use instead is:
var pk = $("tr[id='row_" + row + "']").attr('data-pk')
var rk = $("tr[id='row_" + row + "']").attr('data-rk')
Try:
var pk = $("tr[id='row_" + row + "']").attr('data-pk');
Since jQuery is messing up your data, you can do:
var rk = document.getElementById('row_' + row]).getAttribute('data-rk');
and you are guaranteed a string.

Categories