I am working with Javascript StopWatch in C# web Aplication. But I don't get output from javascript. Below is my code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" language="JavaScript">
var state = 0;
function startstop() {
if (state == 0) {
state = 1;
then = new Date();
then.setTime(then.getTime() - ms);
} else {
state = 0;
now = new Date();
ms = now.getTime() - then.getTime();
document.stpw.time.value = ms;
}
}
function swreset() {
state = 0;
ms = 0;
document.stpw.time.value = ms;
}
function display() {
setTimeout("display();", 50);
if (state == 1) {now = new Date();
ms = now.getTime() - then.getTime();
document.stpw.time.value = ms;
}
}
</script>
</head>
<body onload="display()">
<form id="form1" runat="server">
<div>
Time:
<input type="text" name="time"/>
<input type="button" name="ssbutton" value="Start/Stop" onclick="javascript:startstop()"/>
<input type="button" name="reset" value="Reset" onclick="javascript:swreset()"/>
</div>
</form>
</body>
</html>
I am new with javascript ,Where I am doing mistake?? Thank You...
Udate:Finally I get the errors and solved it. Here is updates solution for someone who want to implement JavaScript Stopwatch in C# Application.
<html>
<head>
<script type="text/javascript">
var ms = 0;
var state = 0;
var then;
var now;
ms = new Date();
function startstop()
{
if (state == 0)
{
state = 1;
then = new Date();
then.setTime(then.getTime() - ms);
}
else
{
state = 0;
now = new Date();
ms = now.getTime() - then.getTime();
document.getElementById('timeInput').value = ms;
}
}
function swreset() {
state = 0;
ms = 0;
document.getElementById('timeInput').value = ms;
}
function display() {
ms = new Date();
setTimeout("display();", 50);
if (state == 1) {
now = new Date();
ms = now.getTime()-then.getTime();
document.getElementById('timeInput').value = ms;
}
}
</script>
</head>
<body onload="display()">
<form>
Time:
<input type="text" name="time" id="timeInput"/>
<input type="button" name="ssbutton" value="Start/Stop" onclick="javascript:startstop()"/>
<input type="button" name="reset" value="Reset" onclick="javascript:swreset()"/>
</form>
</body>
</html>
Thanks For All your help.
Here are some first steps: (This doesn't mean that everything will work, but it will sure help.)
As JohnFx pointed out, make sure the HTML is in good shape.
Give your "text" input called "time" an ID.
<input type="text" name="time" id="timeInput"/>
Reference the element using getElementById()
document.getElementById("timeInput").value = ...
If things don't behave properly, put alert(...) statements in the javascript to see where its going and what values it's coming up with.
Well, one problem is this line:
<inputtype="button"name="ssbutton"value="Start/Stop" onclick="javascript:startstop()"/>
I think you need a few extra spaces in there.
Also you refernce document.stpw.time several times, but I don't see stpw in your html.
onclick=..., onload=... is bad.
javascript: is useless.
language=JavaScript is useless
runat=server is useless.
you don't have a title and therefore don't have valid HTML.
your state and functions are global
you don't use var ms = ...
document.stpw doesn't exist.
You probably meant to name your form document.stpw and document.<formName> is bad. Use document.forms.stpw instead.
setTimeout(string) is bad.
you don't end your if (...) {now = new Date(); with an }
Related
I'm trying to use CefSharp browser control at WinForms application along with the LocalStorage mechanism.
The problem is that the browser control in the application changes to LocalStorage don't affect other browser windows and it doesn't get changes from other chrome browser windows. The HTML works inside native chrome browser and changes localstorage and get changes notifications. What do I miss?
C# Code:
public Form1()
{
InitializeComponent();
CefSharp.Cef.Initialize();
_browser = new ChromiumWebBrowser(URL_TO_LOAD);
_browser.BrowserSettings = new CefSharp.BrowserSettings()
{
ApplicationCacheDisabled = false,
FileAccessFromFileUrlsAllowed = true,
JavascriptDisabled = false,
LocalStorageDisabled = false,
WebSecurityDisabled = true,
JavaScriptOpenWindowsDisabled = false,
JavascriptDomPasteDisabled = false
};
_browser.Load(URL_TO_LOAD);
splitContainer1.Panel1.Controls.Add(_browser);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=620"/>
<title>HTML5 Demo: Storage Events</title>
</head>
<body>
<div>
<p>
<label for="data">Your test data:</label> <input type="text"
name="data" value="" placeholder="change me" id="data" />
</p>
<p id="fromEvent">Waiting for data via<code>storage</code>event...
</p>
</div>
<SCRIPT type="text/javascript">
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
</SCRIPT>
<script>
alert("localStorage: " + localStorage);
var dataInput = document.getElementById('data'), output = document
.getElementById('fromEvent');
addEvent(window, 'storage', function(event) {
alert('change notification');
if (event.key == 'storage-event-test') {
output.innerHTML = event.newValue;
}
});
addEvent(dataInput, 'keyup', function() {
localStorage.setItem('storage-event-test', this.value);
});
var curStorageVal = localStorage.getItem('storage-event-test');
if(curStorageVal != null && curStorageVal != '')
{
output.innerHTML = curStorageVal;
}
</script>
</body>
</html>
Unless you set a path for the cache location in a CefSharp.CefSettings object and pass it to the Cef.Initialize() method, every time your app is started, the browser(s) will create a new cache instance, which will be discarded when your app exits.
The cache instance also holds your localStorage data, as well as any cookies (you might want to keep a user signed in?) and other things as well.
I had the same problem, but found a solution here: https://github.com/cefsharp/CefSharp/blob/v39.0.2/CefSharp.Example/CefExample.cs#L30-L32
One minimal solution is to add this to your application's startup procedure, like in your Program.Main or in your case, your Form1 class's constructor:
var settings = new CefSharp.CefSettings
{
CachePath = "cache"
};
CefSharp.Cef.Initialize(settings);
1.Get these from NuGet package manager :
using CefSharp;
using CefSharp.WinForms;
2.Create instance for you CefSetting :
CefSettings settings = new CefSettings();
settings.CachePath = #"C:\localstorage";
I have a form with id="form1" inside this form i have a graph.Now i am using html2canvas to get the image of this form1.Here is my code..
<script type="text/javascript">
$(document).ready(function () {
$('#add_button').click(function () {
alert("hiii");
$('form1').html2canvas();
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue, { elements: { length: 1} });
var img = canvas.toDataURL();
window.open(img);
alert("Hello");
});
});
</script>
<form id="form1" runat="server">
<div style="padding-left:150px">
<asp:Literal ID="FCLiteral1" runat="server"></asp:Literal>
</div>
<div style="padding-left:350px"><b>Demo</b></div>
</form>
<input type="submit" id="add_button" value="Take Screenshot Of Div" " />
So my question is how can i save this image into my system hardisk..Please help me.
System hardisk? I did not understand, server or client?
CLIENT
If you want the user to download the image automatically, you will need to modify the Data URI scheme
Try this:
Add in css
#myHideFrame {
position: absolute;
top: -9999px;
width: 1px;
height: 1px;
}
Add in Javascript
var img = canvas.toDataURL();
var frame = document.getElementById("myHideFrame");
if(!frame) {
frame = document.createElement("iframe");
frame.id = "myHideFrame";
document.body.appendChild(frame);
}
frame.src = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");
Unfortunately this example does not show the name, for this you will have to do something like this (user need click in link):
var img = canvas.toDataURL();
var link = document.createElement("a");
link.download = "photo.png"; //Setup name file
link.href = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");
document.body.appendChild(link);
SERVER
If you want to save on the server then you need to use Ajax, example with Jquery:
Javascript file:
var img = canvas.toDataURL().replace(/^data[:]image\/(png|jpg|jpeg)[;]base64,/i, "");
$.ajax({
"type": "POST",
"url": "upload.aspx/UploadImage",
"data": {
"imageData": img //Send to WebMethod
}
}).done(function(o) {
console.log(["Response:" , o]);
});
Your upload.aspx.cs file need:
...
[WebMethod()]
public static void UploadImage(string imageData)
{
string fileNameWitPath = "custom_name.png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);//convert from base64
bw.Write(data);
bw.Close();
}
}
}
...
See details: http://www.dotnetfunda.com/articles/show/1662/saving-html-5-canvas-as-image-on-the-server-using-aspnet
A much simpler solution to save an image on the Client side will be to generate an image data and append it to the <a> tag with download attribute on it.
Here is my example:
HTML:
<a href="#" class="downloadAsImage hide" download>Download</a>
JS:
$(function() {
html2canvas($('.main'), {
onrendered: function(canvas) {
$('.downloadAsImage').attr('href', canvas.toDataURL()).removeClass('hide');
}
});
});
Side note: bare in mind that you can't click $('.downloadAsImage') via JS as it has download attribute on it.
Im doing a web application in C# and ASP.NET MVC4.
Im having a problem with loading a map on one of my view pages...
I have the map on my Details page and the you go from Index page to Details page.
This is some of my code:
<div id='myMap' style="position:relative; width:400px; height:400px;">
</div>
<div>
<input type="button" value="createWalkingRoute" onclick="createDirections();" />
</div>
<div id='directionsItinerary'> </div>
#section scripts{
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'mykey' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createWalkingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to walking
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.walking });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle, WA' });
directionsManager.addWaypoint(seattleWaypoint);
var redmondWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond, WA', location: new Microsoft.Maps.Location(47.678561, -122.130993) });
directionsManager.addWaypoint(redmondWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createWalkingRoute });
}
else {
createWalkingRoute();
}
}
getMap();
</script>
}
When you go first go on the Details page the map doesn't load. However if the page is then refreshed, then the map loads after. So to me this is some sort of loading problem. But after trying for few hours Im absolutely stuck.
Can anyone help? thanks
put the getMap() call into some place where it will be called after the page is loaded, for example the body onload event. If you are using jquery, $(document).ready().
In the JavaScript below I have a problem in that the JavaScript applies only to one text box not to all the text area's because the ID generated in the html is different for all text area's. Any help regarding to this
<font>Maximum Number of characters for this text box is 255.<br>
<textarea runat="server" id="txtAnswerMain" onkeypress="return taLimit(this)" onkeyup="return taCount(this,'myCounter')"
name="Description" rows="7" wrap="physical" cols="40">
</textarea>
this is the java script i am using it works for single text area but when i apply to dynamically created text area it does not work
<script language="Javascript">
maxL = 100;
var bName = navigator.appName;
function taLimit(taObj) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
}
else { objCnt.innerText = maxL - objVal.length; }
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
If I dynamically add a textarea using JQuery it works fine.
<script type="text/JavaScript">
$(document).ready(function(){
$('#divToAddTo').append('<textarea id="txtAnswerMain2" onkeypress="return taLimit(this)" onkeyup="return taCount(this,'myCounter')" name="Description" rows="7" wrap="physical" cols="40">');
$('#divToAddTo').append('</textarea>');
});
</script>
I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.