I'm try to run this function, which grabs all the checked checkbox values in to a comma separated string, and converts "," in to ", ", so it reads better. The problem is I'm getting a strange error:
$('.name_boxes').live('click', function() {
var all_boxes = $('.name_boxes');
var all_boxes_values = []
for (var i = 0; i < all_boxes.length; i++) {
if (all_boxes[i].checked) {
all_boxes_values.push(all_boxes[i].value)
}
}
var all_boxes_values_clean = all_boxes_values.replace(/,/g,", ");
alert(all_boxes_values_clean);
});
The console error says:
Uncaught TypeError: Object Aaron Ramsey,Aaron Renfree has no method 'replace'.
I'm not getting the alert box.
This is a bit beyond me, can anybody explain what I'm doing wrong?
Although alert(some_array) prints a string representation of the array, the array itself is not a string. Thus, it does not have .replace. alert is forced to convert it into a string because the alert box can only show characters.
You can simply join using a custom separator, though. join is a function of arrays:
var all_boxes_values_clean = all_boxes_values.join(", ");
As a side note, I recommend console.log over alert because it:
shows the actual object/array instead of a string representation (especially useful with objects instead of the useless [object Object] you receive with alert)
frees you from closing the popup each time
keeps track of other logs so that you have an actual log of logs
all_boxes_values is an array, not a strings and thus it has no replace method.
Try
var all_boxes_values_clean = all_boxes_values.join(", ");
If you insist on performing regular expressions, convert an array to string first: all_boxes_values.toString().
Related
I am storing two items in sessionStorage, an integer and a string array. I can see the items in Chrome Dev Console (Application - sessionStorage) and they are correct.
The values as it shows now in the Chrome Dev Console are:
HTTP_Index 4
HTTP_History ["Start","text_14","text_7","text_10"]
In a javascript function, I retrieve them from sessionStorage:
var HTTP_Index = sessionStorage.getItem(HTTP_Index);
var HTTP_History = sessionStorage.getItem(HTTP_History);
p_Index = JSON.parse(HTTP_Index);
p_History = JSON.parse(HTTP_History);
I decrement the index:
p_Index = p_Index - 1;
console.log("HTTP_Index Now " + p_Index);
and the log shows that the value is now 3.
Next I store the value p_Index back to sessionStorage:
sessionStorage.setItem("HTTP_Index", JSON.stringify({ "p_Index" });
Whether I enclose p_Index in quotes or not, the dev console now shows the function as "undefined."
Next I tried to do it like this:
sessionStorage.setItem("HTTP_Index", JSON.stringify({ "p_Index" });
but same problem. So finally I tried this:
var obj = { HTTP_Index: p_Index };
var objJSON = JSON.stringify(obj);
sessionStorage.setItem(objJSON);
But the Chrome dev console shows:
Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present.
What am I doing wrong in using JSON.stringify for sessionStorage.setItem?
Thanks for any help.
When using .setItem you must set a key, and then the value you want to store.
In the case of your first example, you're doing this but have made a simple typo. Also you want to stringify the contents in p_Index, not the string "p_index", so, you need to remove your quotes around it when stringifying:
sessionStorage.setItem("HTTP_Index", JSON.stringify(p_Index)); // <-- missing this closing bracket
And so you'll get a syntax error here.
In the case of your second example (attempt), you're not using valid syntax as you're setting an object with no value.
In your third example, you're trying to set the value to be the stringified object (so your value is just the string, not the object), and so you're not specifying a key. To do this you can use:
var objJSON = JSON.stringify(p_index);
sessionStorage.setItem("HTTP_Index", objJSON);
In your latest example:
var obj = { HTTP_Index: p_Index };
var objJSON = JSON.stringify(obj);
sessionStorage.setItem(objJSON);
sessionStorage.setItem first argument must be the key which you want to set and the 2nd is the data which you are going to store.
So you miss the key/name.
In my JS code I'm using the following method for displaying a table on my webpage:
function display(data) {
var photoUrls = data.photoUrls;
var tbl=$("<table/>").attr("id","mytable");
for(var i=0;i<photoUrls.length;i++)
{
console.log("single row: "+photoUrls[i]);
var row = "<tr><td>"+photoUrls[i]+"</td></tr>";
$("#mytable").append(row);
}
var outcome = "<h4>Photo URLs:</h4>";
$('#feedback').html(outcome+tbl);
}
and instead of seeing the table, all I see is:
Photo URLs:
[object Object]
That is weird because the console log shows me appropriate names in the console, so I expected it to display table properly. What's wrong with my code then?
In your console.log, you're concatenating strings. In your last line, you're trying to use + between a string and an object. This causes the object to be converted to a string via .toString(). Objects usually stringify to "[object Object]".
The simplest fix (though not necessarily the best) is to use this instead:
function display(data) {
var photoUrls = data.photoUrls;
var tbl=$("<table/>").attr("id","mytable");
for(var i=0;i<photoUrls.length;i++)
{
console.log("single row: "+photoUrls[i]);
var row = "<tr><td>"+photoUrls[i]+"</td></tr>";
tbl.append(row); /* fix 1 */
}
var outcome = "<h4>Photo URLs:</h4>";
$('#feedback').append(outcome).append(tbl); /* fix 2 */
}
#mytable doesn't exist in the document thus $('#mytable') produces an empty jQuery collection so the trailing .append() doesn't achieve anything. (jQuery doesn't usually fail when an operation is performed on an empty collection so this can catch new developers off guard.)
Rather than trying to concatenate strings, just append them to the target directly. (jQuery does some magic so it can usually accept strings, elements, or jQuery collections.)
I'm having problems why my .split() function.
somehow when i splay my line the first [0] element in the array can be accessed but the 2nd [1] can't
I have the following string:
,{"relationID":"000001","recID":"1d2712eb-4f08-4b4f-b6e9-600c9631b503"
And the code below is how i try to split this (tempArray contains a x number of strings like the above):
var templine = tempArray[i].substr(1, tempArray[i].length);
//alert(templine);
var line = templine.split(',');
var s1 = line[0].split('"')[3];
var s2 = line[1].split('"')[3];
when i use alert(s1) or alert(s2) i do get the value however, the folowing error always occurs on the last line (var s2):
caught TypeError: Cannot read property 'split' of undefined
this causes the rest of my script to crash and it won't finish what it's supposed to, displaying an empty page.
My question, what is going wrong here? why does s1 function properly and s2 which is exactly the same except for the index of the line array crash my script.
I want to emphasise when i use the alert function to check the value of my variable s1 and s2 they do contain the right value.
EDIT:
maybe a nice bonus since there might be an easyer way.
after I've gotten the values s1 and s2 i want to put them in a map like so:
map[s2] = s1;
as you can probably tell the string i use is the result of splitting 1 humongous string on ('}'). the code displayed here is what i do when looping trough this array.
That can only be caused by a attempt to access element on the array that is really undefined. Probably your input is not what you are expecting.
Check if line.length > 1 before you try to read those indexes of the array.
As it seems to be a JSON, may be you should try to parse the JSON, it would make your code more readable and reliable. Check JSON.parse browser compatibility before using it (IE8+).
For example:
var data = JSON.parse('{ "field1": "value1", "field2": "value2" }');
var s1 = data['field1'];
var s2 = data['field2'];
Hope I've helped.
var teksts= (document.getElementById("teksts").value);
letter=document.getElementById("letter").value;
var results = teksts.split(" ");
document.getElementById("1").innerHTML = results
var count = new Array
for(var i=0; i<results.length; i++)
{
var first= new String (results[i])
for (var j=0; j<first.length; j++)
{if (first.CharAt(j)==letter)
{count [i]++}
}
I have this piece of code in Javascript that is supposed to read a string from HTML and a letter and then find which one of the words has the most of this type of letters in it. So i tried to keep it simple, split the string into an array, have each of the array elements defined as a string and then have a loop go through every letter and if it is the letter that is asked for, mark it in count array.
The problem is, even though i specifically define that the word (in variable first) should be a string and then try to use CharAt method for it to get the specific symbol, i get an error "Uncaught TypeError: Object [object String] has no method 'CharAt' "
I can't with all my googling skills understand why the method won't work for me.
The method name is charAt not CharAt, note the small c
Suggestion 1: var count = new Array should have been var count = []; Its always better to create empty arrays like this, because Array can be anything at runtime as it can be overwritten.
Suggestion 2: It is a good practice to mark the end of lines with ; (semi colon) in javascript.
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.