Use indexOf to detect if the value has comma - javascript

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

Related

How to find number string inside delimited string

I've been working on this all day and just cannot seem to figure out why it won't work. I am grabbing a delimited string from a hidden field. I need to test to see if a string is contained in that original string. The simple example below should work but does not.
var orgStr = "091300159|091409568|092005411";
var newArr = orgStr.split('|');
console.log(orgStr);
console.log(newArr);
console.log("inarray? " + $.inArray(newArr, "092005411"));
It seems to work if I can wrap quotes around each value but all attempts are unsuccessful.
In JQuery's inArray function the value needs to come before the array.
console.log("inarray? " + $.inArray("092005411", newArr));
You could also use the native indexOf operator as such:
console.log("inarray? " + newArr.indexOf("092005411"));
Both should output "inarray? 2" to the console.
Have a look at the $.inArray docs.
The first argument is the value and the second the array. You did the opposite.
$.inArray("092005411", newArr) correctly returns 2.

jQuery update doesnt work but javascript does

I've been trying different methods of getting my page to update one input value when I select something from another. When I try it one way using javascript it works fine, another way via jQuery it doesn't and I honestly don't understand why, could someone point out what I'm missing?
This Javascript works fine: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
document.getElementById(objID).value = id
}
But this jQuery doesn't: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
The objects on the being used/references are all loaded in during the page load via AJAX calls etc, is this something to do with what's causing the issue?
Thanks for any pointers, if anyone has any good links to read explaining this stuff better I'd be very appreciative! :)
Also tried this but still no dice...
$(document).ready(function(){
function updateHiddenInput(id, num){
var objID = "any[" + num + "].id";
$("#"+objID).val(id);
}
});
There's a difference between a jQuery selector and document.getElementById. The second does less, so it knows that whatever you give it will be looked at as an id. For example:
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
What will this look for? Let's presume num is 1, say:
$('#any[1].id').val(id);
This looks for an element with the id #any, an attribute 1, and a class id, because the characters []. all have special meanings in a selector. To demonstrate this, run the following line of code in the browser console:
$('<div id="any" class="id" 1="foo"/>').is('#any[1].id') // returns true
The best way to do this selection is to do the selection with document.getElementById, and then wrap it in the jQuery constructor:
$(document.getElementById(objID)).val(id);
It is possible to escape the special characters with \\, but it becomes increasingly unwieldy and hard to (a) write and (b) read.
You have this:
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
This results in objID having some value like any[3].id, so your jQuery looks like this: $("#any[3].id").val(id); jQuery interprets the .id as a class. Escape it like this:
function youPickedThis(id, num){
var objID = "any\\[" + num + "\\]\\.id"
$("#"+objID).val(id);
}
You should escape square brackect and dot
var objID = "any\\[" + num + "\\]\\.id";
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").
REFERENCE
http://forum.jquery.com/topic/jquery-jquery-wont-recognise-attribute-names-containing-square-brackets#14737000000283511
As others have mentioned, there are differences between jQuery selector and document.getElementById. As jQuery selector has to parse the string and some characters like [,] have special meaning while document.getElementById treats all this as part of an id. You could try escaping those special characters as mentioned by others. Here I give another solution.
You could try id attribute selector. It does something similar to document.getElementById
function youPickedThis(id, num){
var objID = "'any[" + num + "].id'"
$("[id="+objID+"]").val(id);
}
DEMO

how to get the base url using regex in javascript

My app is going to work in multiple env, in which i need to get the common value (base url for my app) to work across..
from my window location how to i get certain part from the start..
example :
http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html
how can i get only:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
my try :
var base = \w([yx]/)
the base only select yx/ how to get the value in front of this?
this part..
thanks in advance..
If 'someother' is known to be the root of your site, then replace
\w([yx]/)
with
(.*\/)someother\/
(note that the / characters are escaped here) which gives a first match of:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
However, a regular expression may not be the best way of doing this; see if there's any way you can pass the base URL in by another manner, for example from the code running behind the page.
If you don't mind disregarding the trailing slash, you can do it without a regex:
var url = 'http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html';
url.split('/', 4).join('/');
//-> "http://xxxxx.yyyy.xxxxx.com:14567/yx"
If you want the trailing slash, it's easy to append with + '/'.
Please try following regexp:
http\:\/\/[\w\.]+\:\d+\/\w+\/
This one should do pretty well
http:\/\/[\w\.]+\:\d+\/\w+\/
Perhaps something like this?
Javascript
function myBase(url, baseString) {
if (url && baseString) {
var array = url.split(new RegExp("\\b" + baseString + "\\b"));
if (array.length === 2) {
return array[0] + baseString + "/";
}
}
return null;
}
var testUrl = "http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html",
testBase = "yx";
console.log(myBase(testUrl, testBase))
;
Output
http://xxxxx.yyyy.xxxxx.com:14567/yx/
On jsfiddle

Trying to covert a variable into its value within a URL

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.

Returning a string from a parallel array

I am sorry for the very newbie question, but this is driving me mad.
I have a word. For each letter of the word, the characters position in one array is found and then returns the character at the same position found in a parallel array (basic cipher). This is what I already have:
*array 1 is the array to search through*
*array 2 is the array to match the index positions*
var character
var position
var newWord
for(var position=0; position < array1.length; position = position +1)
{
character = array1.charAt(count); *finds each characters positions*
position= array1.indexOf(character); *index position of each character from the 1st array*
newWord = array2[position]; *returns matching characters from 2nd array*
}
document.write(othertext + newWord); *returns new string*
The problem I have is that at the moment the function only writes out the last letter of the new word. I do want to add more text to the document.write, but if I place within the for loop it will write out the new word but also the other text inbetween each word. What i actually want to do is return the othertext + newWord rather than document.write so that I can use it later on. (just using doc.write to text my code) :-)
I know its something really simple, but I cant see where I am going wrong. Any advice?
Thanks
Issy
The solution is to build newWord within the loop using += instead of =. Just set it to an empty string before the loop.
There are other problems with this code. Variable count is never initialized. But let's assume that loops should be using count instead of position as it's principal counter. In that case, if I am not mistaken, this loop will just generate array2 as newWord. First two lines of loop's body cancel each other in a matter of speaking, and position will always be equal to count, so letters from array2 will be used sequentially from beginning to the end.
Could you provide one example of input and desired output, so that we understand what you actually want to accomplish?
A good way of structuring your code and your question is that you define a function that you need to implement. In your case this could look like:
function transcode(sourceAlphabet, destinationAlphabet, s) {
var newWord = "";
// TODO: write some code
return newWord;
}
That way, you clearly state what you want and which parameters are involved. It is also easy to write automatic tests later, for example:
function testTranscode(sourceAlphabet, destinationAlphabet, s, expected) {
var actual = transcode(sourceAlphabet, destinationAlphabet, s);
if (actual !== expected) {
document.writeln('<p class="error">FAIL: expected "' + expected + '", got "' + actual + '".</p>');
} else {
document.writeln('<p class="ok">OK: "' + actual + '".');
}
}
function test() {
testTranscode('abcdefgh', 'defghabc', 'ace', 'dfh');
}
test();

Categories