Show value of variable from json string - javascript

I have a for-loop:
var player = 5;
for (var i = 0; i <10; i++) {
$("#id").append('<div class="game_content_text">'+json_var[i].content+'</div>');
}
The json looks like:
"content":"<script>player</script>"
Now I only want to to write down the 5 but nothing is showing...
Edit: I simplified it. Why I have to show more code? The problem is in this lines...
For example if i show a simple text from the json ("content":"example!") it works...
For explanation:
I have a buck of personal questions in the JSON Feed.
Example: "Hello 'name_variable' how are you?"
And in the the 'name_variable' i want show random names...

If we append script tag dynamically then you need to call that code which is inside newly added script.
A script tag result cannot be assign a variable or it cannot be shown as result.
You can try following example
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});

I'd like to get more code simply for the fact that I can understand the context better, because your code is rather confusing.
So apparently you try to display the value player in all your appended elements?
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + player + '</div>');
}
Otherwise, if you really need that script to be stored in the json (for some reason). I'm assuming the class "game_content_text" is only used for this.
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + json_var[i].content + '</div>');
}
"content": "<script>$('.game_content_text').append(player);</script>"
I'm not all that familiar with jQuery, but that should work.
Also, I really do not recommend this.

Related

Search For Text in Div

I'm trying to make a runnable console command through Chrome that searches for the word "takeID", and then grabs the content immediately after it between = and & from a div class.
What I have so far doesn't work because I'm very bad at JS so any help would be appreciated. Below is what I have so far:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var searchValue = "takeID";
for(var i=0;i<iframe.length;i++){ if(iframe[i].innerHTML.indexOf(searchValue)>-1){}};
var subString = iframe.substring( iframe.lastIndexOf("=")+1, iframe.lastIndexOf("&"));
console.log(searchValue+"="+subString);
An example of the div class it would be searching would look like:
<div class="activity activity-container-html5" config="{example text;takeID=cd251erwera34a&more example text}">
There are two issues with the code. The first issue is the searchValue posts to the console as whatever is in between the takeID, and not the actual result from searching. The second issue is that the code to search between = and & doesn't work at all and I don't know why. What is wrong with the code?
I just want an output that would post to the log or a popup window saying:
takeID=cd251erwera34a
EDIT:
Something else I thought of was how would you be able to just parse the div and then search for what is in between "takeID=" and "&"? I tried this but I was getting the error "Uncaught TypeError: iframe.lastIndexOf is not a function".
var iframe=document.getElementsByClassName("activity activity-container-html5");
var subString = iframe.substring( iframe.lastIndexOf("takeId=") + 1, iframe.lastIndexOf("&") );
console.log(subString);
I looked this up and I see this is because what it is trying to process is not a string but I'm not sure why that is or how to fix it.
I don't know about you but the best would be to use json directly inside the html tag like this:
<div class="activity activity-container-html5" config="{'example':'text', 'takeID':'cd251erwera34a', 'other':''}">
Or use an array and check manually if the one you are checking is the one you want, like this:
function config(element, searchValue) {
if (element.hasAttribute('config')) {
var configData = JSON.parse(element.getAttribute('config'));
var res = "";
for (var i = 0; i < configData.length; i++) {
if (configData[i].includes(searchValue)) {
res = configData[i];
break;
}
}
return res;
}
}
el = document.getElementsByClassName('activity activity-container-html5');
for (var i = 0; i < el.length; i++) {
console.log(config(el[i], "takeID"));
}
<div class="activity activity-container-html5" config='["example=text", "takeID=cd251erwera34a", "othertext=here"]'>
The array-type (second example) is most likely to work better than the simple json one (first one).
I figured out what I needed to do. Below is working code:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var div = "";
for(var i=0;i < iframe.length; i++){
div += (iframe[i].outerHTML);
}
var take = /takeID=([a-z0-9]*)&/;
var capture = div.match(take);
var matchID = capture[1];
console.log(matchID);
window.alert("takeID=" + matchID);

Phantomjs change object property inside page evaluate

I'm new to JavaScript and PhantomJS. I'm trying to store links from a webpage and then modify. The problem is that I can't modify my array after page.evaluate.
var player = 0;
var links = page.evaluate(function() {
var a = document.querySelectorAll(".link[rel='nofollow']:not(#bg)");
for(var i =0; i < a.length; i++) {
array.push({
"html":a[i].innerHTML,
"link":a[i].href
}
);
}
return array;
});
//Not setting 1 as a value
links[player]["link"] = 1;
I think that It's happening because I have already set player value when the function is executed, but is there way that I could modify this value?
Your current code replaces a copy of a copy of a reference to the actual data that you want to change. Of course, that cannot work.
If you want to change a property/content on a page, then you need to access the page and change it:
var player = 0;
page.evaluate(function(player) {
var a = document.querySelectorAll(".link[rel='nofollow']:not(#bg)");
a[player].href = "1";
}, player);
I don't think that "1" is an appropriate value for the href value, but it looks like that is what you want to do.

How do I reformat and output a javascript string into array?

Still learning... again sorry if this sounds stupid:
I have 2 variables "timestamps" and "clicks" and a string of numbers:
var myData = {
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
I'm trying to restructure that into an array in this format:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],
Here is what I have so far: http://jsfiddle.net/3UsP6/1/
Javascript:
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = test;
for (var i = 0, l = myData.timestamps.length; i < l; i++)
{
output.push([myData.timestamps[i], myData.clicks[i]]);
}
HTML:
<body onload="javascript:alterText()">
<a id="test"></a>
</body>
I need to output the variable into the body of the page but I can't get it to display. What am I doing wrong?
Before anything else, if you are debugging, you are better off using the debugger of the browser (F12 in most browsers). Use console.log() to output to the console to see values. Breakpoints would be better since they pause code, and you can inspect values at that moment.
Now, for the mistakes you made:
Your output is test which is an <a>. You can't do a push since that's not an array. What you can do is create an array, fill it with values, and do a JSON.stringify to turn it into a string.
You should use document.get* functions, like document.getElementId() to refer to DOM elements. Though browsers do expose globals for elements with ids, you should avoid that.
This should fix it:
function alterText() {
var myData = {
"timestamps": [1369008000, 1369094400, 1369180800],
"clicks": [1, 2, 3]
};
var output = [];
var link = document.getElementById('test');
for (var i = 0, l = myData.timestamps.length; i < l; i++) {
output.push([myData.timestamps[i], myData.clicks[i]]);
}
// Output to console
console.log(output);
// Convert array to text and output to element
link.innerHTML = JSON.stringify(output);
}
A big problem with the jFiddle is you don't include jQuery. When trying to get an element by id, you cannot just reference it by name. Below is a revised version that does output what you want (though not in a nice format or anything).
$(function() {
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = $('#test');
for (var i = 0; i < myData.timestamps.length; i++) {
output.append([myData.timestamps[i], myData.clicks[i]]);
}
});

XML file in Javascript, getElementByAttribute

Let's suppose I have an XML file like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<MIDIFile>
<Event>
<Absolute>0</Absolute>
<NoteOn Channel="1" Note="40" Velocity="64"/>
</Event>
<Event>
<Absolute>236</Absolute>
<NoteOff Channel="1" Note="40" Velocity="0"/>
</Event>
</MIDIFile>
Thanks to some great tutorial I now know how to get these values in my javascript.
For example, I can iterate thru all the "Events" tag and get the "Absolute" value like this:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// make an array with all the events from the xml file
var events = xmlDoc.getElementsByTagName("Event")
for (var i = 0; i<events.length; i++)
console.log(events[i].getElementsByTagName("Absolute")[0].childNodes[0].nodeValue)
this will return
0
236
Now, how the hell can I access the "NoteOn" attribute and get its values? I want to iterate thru all the Events in the XML, see if they contains NoteOn or NoteOff and load an array with all the notes, their duration, velocity and channels.
Please help me! getElementsByTagName("NoteOn") just doesn't work... If it might help, here are some screenshot of what happens if I console.log(xmlDoc)
Thanks a lot in advance!
edit in response to an answer. As I try to do this:
var noteon = xmlDoc.getElementsByTagName('noteon');
console.log(noteon)
the result is just this one
[]
re-edit:
If I write "NoteOn" instead of "noteon" it works!
var noteon = xmlDoc.getElementsByTagName('noteon');
var note = new Array;
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
}
Edit:
If noteon = [] then you have 2 options you can put the whole thing in a try catch, not the best thing to do in javascript, or you can put it in an if statement. Something like this should work:
var noteon = xmlDoc.getElementsByTagName('noteon');
var noteoff = xmlDoc.getElementsByTagName('noteoff');
var note = new Array;
if(noteon != []){
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
} else if(noteoff != []){
for(var i = 0; i < noteoff.length; i++){
note[i] = noteoff[i].getAttribute('Note'); // or any of the attributes you want to get
} else{
return; //makes sure the function returns to the call even if nothing was found
}
}

Please assist me with this simple script

I am new to JavaScript and would like to ask for some help with my simple script.
What I am trying to do is to retrieve and display the values of all list item elements in the unordered list with the help of the (for) loop. I was able to get the script display all list items in the alert window one by one. But the problem is that I need values of all list elements displayed in a table row way. Like this:
Monday
Tuesday
Wednesday
.......
Here is what I have in my script:
<script language="JavaScript">
<!--
function process() {
a = document.getElementsByTagName('li')
for (i = 0; i < a.length; i++) {
alert(a[i].childNodes[0].nodeValue);
}
}
//-->
</script>
And here is HTML code:
<body>
<ul>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
</ul>
<input type="button" value="Submit" onclick="process()" />
</body>
If that's possible at all would anyone please also explain where I am wrong in my script? Why all 3 list item values can't be shown in the alert window at once?
Thanks a lot!
First, create a string variable: var all_at_once = "". Then, add the contents of the nodeValue. Finally, alert this variable:
function process(){
var a = document.getElementsByTagName('li')
var all_at_once = "";
for(i=0;i<a.length;i++){
all_at_once += a[i].childNodes[0].nodeValue + " ";
}
alert(all_at_once);
}
The alert shows repeatedly because that is what a for loop does... it loops! The loop will iterate over the array of elements returned by getElementsByTagName, executing the loop body once for each element in that array.
If you wanted to display one alert, an option would be to build up a string containing the appropriate text, and alert it afterwards:
var yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
Some other notes on your code... you should almost always declare variables with the var keyword to prevent them leaking into the global scope. You should also always end lines with semi-colons:
function process(){
var a = document.getElementsByTagName('li'),
yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
}
<script language="JavaScript">
<!--
function process(){
var data = '';
a=document.getElementsByTagName('li')
for(i=0;i<a.length;i++){
data = data + '\n' +(a[i].childNodes[0].nodeValue);
}
alert(data);
}
//-->
</script>
You need to call alert only once if you need 1 popup with all the text.
function process()
{
var a = getElementsByTagName('li'),
text = '';
for( i = 0; i < a.length; i++ )
{
text += a[i].childNodes[0].nodeValue + '\n';
}
alert( text );
}
You can process the days in whatever manner you like by storing them in an array first, and then iterating:
var days = new Array();
var a = document.getElementsByTagName('li')
for(var i = 0; i < a.length; i++) {
days.push(a[i].childNodes[0].nodeValue);
}
for (i=0; i < days.length; i++) {
// process the day
}
See: http://jsfiddle.net/jkeyes/Cfg4k/ for a working example.
These few adjustments to your function should produce the result you want. Good luck!
What changed: 1) Set up an empty string var 2) Instead of alerting each value, just append them to the string var you created earlier 3) Finally, alert the newly created (concatenated) string!
function process() {
a = document.getElementsByTagName('li');
var days = new String("");
for (i = 0; i < a.length; i++) {
days = days+(a[i].childNodes[0].nodeValue)+"\n";
}
alert(days);
}
Now I see there have been tons of answers since opening this thread... but maybe all the different solutions will help you in different ways.

Categories

Resources