I was trying to get a run-time value(msg.payload) from a function node(node-red) and supply it to a template node(node-red) to display appropriate image according to the input.I used the below code,but the image is not changing according to the choice of input. Below is the code. Please take a look and provide me some insights or what needs to be changed to make it work.
<html>
<head>
<script type="text/javascript">
function displayImage() {
var j=parseInt({{payload}});
document.getElementById("img").src = images[j];
}
function startTimer() {
setInterval(displayImage,3000);
}
var images = [];
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload="startTimer()">
<img id="img" src="image1.jpg"/>
</body>
</html>
Use the console.log(message)and check:
the {{payload}} parameter should be an integer as you expected
the value of J parameter, after its assignment, should an integer between 0-2
You are dealing with NodeRED. The easiest way to learn about your payload parameter is to use a Debug node (the dark green one) and attach it to the same output as the template node. You then will very quickly see what it is made of. Most likely your payload is a JSON object. Something like this:
{ "name" : "Peter",
"color" : "Blue",
"image" : "2"
}
... or similar.
Then you just change that content in {{ }} to reflect the variable inside the JSON object that has the number you are interested in. Like:
{{payload.image}}
Double check your function node. If it doesn't end with a return statement (typically return msg) you simply won't have any input.
Related
I'm using FileStack on my website, according to FileStack Docs I have this actually:
<iframe id="framefile" width="700" height="500" frameborder="0">
<p>Your browser does not support iframes.</p>
</iframe>
<div id="files"></div>
And in javascript side:
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="http://api.filepicker.io/v2/filepicker.js"></script>
<script type="text/javascript">
filepicker.setKey("myAPIKey");
filepicker.pickMultiple(
{
mimetype: '*/*',
language: 'es_mx',
container: 'framefile',
services: ['COMPUTER','GOOGLE_DRIVE','DROPBOX']
},
function(Blobs){
console.log(JSON.stringify(Blobs));
},
function(FPError){
console.log(FPError.toString());
});
</script>
I need to get only URL files values and put it in a div. I tried this:
<script type="text/javascript">
filepicker.setKey("myAPIKey");
filepicker.pickMultiple(
{
mimetype: '*/*',
language: 'es_mx',
container: 'framefile',
services: ['COMPUTER','GOOGLE_DRIVE','DROPBOX']
},
function(Blobs){
console.log(JSON.stringify(Blobs));
var result = JSON.stringify(Blobs, ['url']);
$('#files').html(result);
},
function(FPError){
console.log(FPError.toString());
});
</script>
I obtain this:
[{"url":"https://cdn.filepicker.io/api/file/--link1--"}]
But How can I obtain URL values but in this way?:
https://cdn.filepicker.io/api/file/--link1--
Anyone have a solution?
You're almost there, are not you?
What about appending [0].url to the object which is returned ?
I mean substituting result = JSON.stringify(Blobs, ['url']); for result = JSON.stringify(Blobs, ['url'])[0].url;
UPDATE
My first anwser is wrong because result in
result = JSON.stringify(Blobs, ['url'])
returns '[{"url":"https://cdn.filepicker.io/api/file/--link1--"}]', which is a string since it comes from a stringifyed variable. Thus, result[0] returns its first character, which is "[". Finaly result[0].url or put differently, "[".url is undefined. (and can hardly be so)
Replace this part:
function(Blobs){
console.log(JSON.stringify(Blobs));
var result = JSON.stringify(Blobs, ['url']);
$('#files').html(result);
}
by
function(Blobs){
$('#files').html(Blobs[0].url);
}
If one wants to get the desired information from a json, one must not stringify it.
Update
Or if you want to display numerous urls, because of multiple files replace the latter method by
function(Blobs){
var displayedUrls = "";
for (i = 0; i < Blobs.length; i++) {
displayedUrls += Blobs[i].url + "<br>";
}
}
$('#files').html(displayedUrls);
Need to dynamically update contents in a div of main page, based on data fetched from other html page
setInterval( function() {
$.ajax({
type:'GET',
url:"url for status",
success : function(data){
console.log(data);
}
})
},3000);
The content of 'data' printed in developer tool console is:
<html>
<style>
</style>
<head>
</head>
<script>
var conns=[{num:1,
id:1,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_1',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
},
{num:2,
id:2,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_2',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
}]
</script>
</html>
Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.
I would recommend using a different transfer type, however, you could use something like this:
function break_out_each_id(){//returns array of indexes where id starts
var i = 0;
id_objs = [];
while data.indexOf('id', i) > -1{
id_objs[i] = data.indexOf('id', i);
i++;
}
return id_objs
}
function find_values(){//pseudo code
use the array of indexes from first index to next index
in that string, do index of each value you are looking for (ConnectionStatus...)
then parse that line after the ':' to get the value.
Do this for each index in indexes array
}
Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.
There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});
I am passing div name in the query string from one html page and retrieving that div name on the other html page. Now I want to display that specific div on the page.My code is
function onLoad()
{
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block"; //error is in this line
}
But I am getting an error as "object expected". please help me
The window.location.search property returns the part of the URL that follows the ? symbol, including the ? symbol.
So for example it might return ?paramname=paramvalue. When you call substring(1) on it you get paramname=paramvalue which is what gets passed to the document.getElementById function which obviously is wrong because such element does doesn't exist on your DOM.
You could use the following javascript function to read query string parameter values:
function onLoad() {
var divname = getParameterByName('divname');
document.getElementById(divname).style.display = 'block';
}
This assumes that you have a query string parameter name called divname:
?divname=some_div_name
Adjust the parameter passed to the getParameterByName function if your query string parameter is called differently.
You might also want to introduce error checking into your code to make it more robust:
function onLoad() {
var divname = getParameterByName('divname');
var divElement = document.getElementById(divname);
if (divElement != null) {
divElement.style.display = 'block';
} else {
alert('Unable to find an element with name = ' + divname);
}
}
What I am suggesting is place your js at the end of the html code (before </body> tag). Do not use a function.
<html>
...
...
...
<body>
...
...
...
<script>
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block";
</script>
</body>
</html>
I have re-written my function and it is working, code is like this
function load()
{
var divname = window.location.search.substring(1);
var params=divname.split('=');
var i=1;
alert(params[i].substring(0));
document.getElementById(params[i].substring(0)).style.display='block';
}
I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".