I am very new to javascript but unfortunately it is what I have to use for a thermometer chart that I'm using. I need to get the value of an ASP label text and then store that into a javascript variable which will be used to set the chart value.
For some reason it is not storing the value at all and the chart obviously doesn't have the value needed. Again I am extremely new to javascript so please be nice. :) Here is what I have so far.
Here is part of the ASPX page:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script>
window.onload = function () {
// Create the Thermometer chart. The arguments are: the canvas ID, the minimum,
// the maximum and the indicated value.
var grossSales = $('#<%= MtdLBL.ClientID %>').next().text;
var thermometer = new RGraph.Thermometer('salesThermometer', 0, 180000, parseInt(grossSales.valueOf))
// Configure the thermometer chart to look as you want.
.Set('chart.gutter.left', 45)
.Set('chart.gutter.right', 45)
.Set('chart.colors', ['rgba(255,0,0,1)'])
.Set('chart.units.pre', '$')
// Now call the .Draw() method to draw the chart.
.Draw();
}
</script>
<link href="Charts/RGraph/demos/demos.css" rel="stylesheet" type="text/css" />
<script src="Charts/RGraph/libraries/RGraph.common.core.js" type="text/javascript"></script>
<script src="Charts/RGraph/libraries/RGraph.thermometer.js" type="text/javascript"></script>
</asp:Content>
And this is from the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TeamID"] == null || Session["TeamID"] == "")
{
Response.Redirect("~/Default.aspx");
}
else
{
//Populate department average
double deptAvg = achievementData.DeptAverage();
DeptAvgValueLBL.Text = deptAvg.ToString("P0");
//Get sales data
Sales getSalesData = new Sales();
MtdLBL.Text = getSalesData.GrossSalesByTeam(Session["TeamID"].ToString());
}
}
var grossSales = $('#<%= MtdLBL.ClientID %>').text();
Note parentheses; text is a function, not a simple value. The next() is out of place unless you want the following control, which doesn't seem right.
Remove the valueOf() call in the thermometer variable definition line. valueOf is used to return a primitive boolean. I'm assuming you're trying to use the grossSales number for something other than a boolean flag.
See http://www.w3schools.com/jsref/jsref_valueof_boolean.asp
Also, as #catfood said, you don't need the .next()
Related
I've a problem with plotting an number array in Plotly. So, we can skip to subject without further ado.
Here is HTML code:
<script src="plotly.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-database.js"></script>
<div class="navbar"><span>Analog Plotter by remidosol</span></div>
<div class="wrapper">
<div id="chart"></div>
<script src="FireConfig.js"></script>
<script>
Plotly.plot('chart',[{
y:[analogval()],
type:'line'
}]);
var cnt = 0;
setInterval(function(){
Plotly.extendTraces('chart',{ y:[[analogval()]]}, [0]);
cnt++;
if(cnt > 300) {
Plotly.relayout('chart',{
xaxis: {
range: [cnt-300,cnt]
}
});
}
},15);
</script>
</div>
</body>
How can I plot number ARRAY that read from Firebase? I changed getData function's return code, once.(like I placed a num array parameter to getData, but it didn't make the plot.ly code work to plot data).
I could read data from Firebase but i couldn't plot it.
Here is view of my website and console:
It reads data but can't plot.
Would you help me please? What's wrong with this code? BTW, Firebase config block is okay, i changed it before create this subject.
I'm waiting for your help. Thank you from now.
Edit:
I can get data and convert it to number by replace and slice methods. It's correct now. But the plot.ly code still don't plot data line.
Following aforementioned function, here is the code below:
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
return arru;
//arru = data.val().analog.split(",").map(Number);
})}
The issue is in your analogval() function. If I'm not mistaken, your current implementation of analogval () doesn't return anything. Your return statement is inside of the callback function that you passed to the .on() method. What you need is to have your analogval() function to return the value of the array.
One way to do this is to create a variable (e.g. array) visible to analogval() and set the value of array to be what you read from Firebase, then return array from analogval():
var array;
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
array = arru;
});
return array;
}
Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);
I am using javascript to set asp:hiddenfield to '1' but not getting set.
I am setting it like this:
<script type="text/javascript">
function uploadComplete(sender, args) {
var myHidden = document.getElementById('<%= HdnFieldEmployeePicture.ClientID %>');
myHidden.value = '1';
}
</script>
from:
<asp:AsyncFileUpload ID="FileUpload1" OnClientUploadComplete="uploadComplete" ClientIDMode="AutoID" UploaderStyle="Modern" runat="server"/>
<asp:HiddenField ClientIDMode="Static" ID="HdnFieldHasFileUploaded" runat="server" />
I am checking it on server side:
if (HdnFieldHasFileUploaded.Value == "1")
{
but not set to 1.
AsyncControl and hidden field are inside UpdatePanel.
Your javascript code will not work because javascript method bindings get broken when your page is partially submitted using asp.net update panel. You need to add following lines of code to get it back to work.
<script type="text/javascript">
function EndRequestHandler(sender, args) {
// bind your methods here
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
</script>
I'm trying to pass a string and call a javascript function from the code behind in vb.net, once I click a button. The javascript is in a separate file.
Below is the code for the button:
/MyProject/myfile.aspx
<HTML>
...
...
<asp:textbox id="txtSearch" runat="server" Width="120px" CssClass="midField"></asp:textbox>
<input class="midBtn" id="btnSearch" type="button" value="Search" name="btnSearch" runat="server">
...
...
<script src='<%= Page.ResolveClientUrl("~/script/functions/myFunc.js")%>' ></script>
</HTML>
/MyProject/myfile.aspx.vb
Private Sub btnSearch_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.ServerClick
Dim searchString As String
searchString = txtSearch.Text
Dim rsname As String = Page.ResolveClientUrl("~/script/functions/myFunc.js")
Page.ClientScript.RegisterStartupScript(Me.GetType(), "mySearch", "mySearch('" & searchString & "')", True)
End Sub
/MyProject/script/functions/myFunc.js
function mySearch(searchString){
// ...
// logic for mySearch
// ...
}
I can't get the javascript function to be called and I need to reference the .js file at the end of my .apsx page. The error I get from the debugger is Uncaught ReferenceError: mySearch is not defined, please help.
If the criterion of choice is a dropdown, probably a better solution (I used jquery) is put the js file at the end of page, and check the dropdown value from javascrpit (here set as variable) and intercept the postback of .NET button:
<script type="text/javascript">
$(document).ready(function () {
var dropdown = 1;
$('.midBtn').click(function () {
if (dropdown == 1) {
mySearch($('.midField').val());
return false;
} else {
// ... postback
}
});
});
</script>
In this case you must be sure that the classes selector (midBtn and midField) are unique.
I'm currently trying to call a JS script in order to export chart from primefaces chart component.
The problem is that the base64str variable seem to be null, and the responsible script for filling this value is not called for some reason :
xhtml code :
<p:chart id="chart" type="line" widgetVar="chart" model="#{cont.lineModel}" style="height:550px;width:1800px">
<p:ajax event="itemSelect" listener="#{cont.itemSelect}" update="growl" />
</p:chart>
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onclick="exportChart();" actionListener="#{cont.submittedBase64Str}"
/>
<h:inputHidden id="b64" value="#{cont.base64Str}" />
<script type="text/javascript">
function exportChart() {
img = chart.exportAsImage();
document.getElementById('hform:b64').value = img.src;
}
</script>
Controller :
public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here.
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
String encoded = base64Str.split(",")[1];
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
// Write to a .png file
try {
RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
ImageIO.write(renderedImage, "png", new File("D:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
Change your onclick attribute to onstart.
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onstart="exportChart();" actionListener="#{cont.submittedBase64Str}" />
That should call the JS function.
EDIT
Also, you need to define img and chart in your function.
chart object is the PrimeFaces JS widget. You define widgetVar:
<p:chart ... widgetVar="chart"
And then you can get the chart object in your JS code like this:
PF('chart')
You need to use the PF function to get widgets since PrimeFaces 4.0.
As a side note, it's better to make your img variable local instead of global:
var img = chart.exportAsImage();
Now img is defined only in the scope of the function.