I am trying to get CKEditor.NET to insert some text into my CKEditor when the page loads.
Private Sub CKEditor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myCKEditor.Load
Dim insertScript As String
insertScript = "<script type=""text/javascript"">window.CKEDITOR.instances.myWidget_myCKEditor.insertText(""test"");</script>"
Dim cManager As ClientScriptManager = Parent.Page.ClientScript
cManager.RegisterStartupScript(Me.GetType, "insertText", insertScript)
End Sub
My page is organized as follows:
myPage (aspx)
myWidget (ascx)
myCKEditor (from an assembly)
I am getting the following error:
TypeError: Cannot read property 'instances' of undefined
It appears that CKEDITOR is not around when this is called. If I open up the JS console and run the insertScript it works as desired.
I have tried attaching this routine to MyBase.Load and Me.Load as well to no avail, and even tried using window.Load = insertScript, all of which produce the same error.
I noticed that no matter what I do, the last thing in the source is the script that initializes CKEditor, ie
....
<script type="text/javascript">window.CKEDITOR.instances.myWidget_myCKEditor.insertText("test");</script>
<script type="text/javascript">
//<![CDATA[
window.CKEDITOR_BASEPATH = '/ckeditor/';
//]]>
</script>
<script src="/ckeditor/ckeditor.js?t=C6HH5UF" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var CKEditor_Controls=[],CKEditor_Init=[];function CKEditor_TextBoxEncode(d,e){var f;if(typeof CKEDITOR=='undefined'||typeof CKEDITOR.instances[d]=='undefined'){f=document.getElementById(d);if(f)f.value=f.value.replace(/</g,'<').replace(/>/g,'>');}else{var g=CKEDITOR.instances[d];if(e&&(typeof Page_BlockSubmit=='undefined'||!Page_BlockSubmit)){g.destroy();f=document.getElementById(d);if(f)f.style.visibility='hidden';}else g.updateElement();}};(function(){if(typeof CKEDITOR!='undefined'){var d=document.getElementById('myWidget_myCKEditor');if(d)d.style.visibility='hidden';}var e=function(){var f=CKEditor_Controls,g=CKEditor_Init,h=window.pageLoad,i=function(){for(var j=f.length;j--;){var k=document.getElementById(f[j]);if(k&&k.value&&(k.value.indexOf('<')==-1||k.value.indexOf('>')==-1))k.value=k.value.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');}if(typeof CKEDITOR!='undefined')for(var j=0;j<g.length;j++)g[j].call(this);};window.pageLoad=function(j,k){if(k.get_isPartialLoad())setTimeout(i,0);if(h&&typeof h=='function')h.call(this,j,k);};if(typeof Page_ClientValidate=='function'&&typeof CKEDITOR!='undefined')Page_ClientValidate=CKEDITOR.tools.override(Page_ClientValidate,function(j){return function(){for(var k in CKEDITOR.instances){if(document.getElementById(k))CKEDITOR.instances[k].updateElement();}return j.apply(this,arguments);};});setTimeout(i,0);};if(typeof Sys!='undefined'&&typeof Sys.Application!='undefined')Sys.Application.add_load(e);if(window.addEventListener)window.addEventListener('load',e,false);else if(window.attachEvent)window.attachEvent('onload',e);})();CKEditor_Controls.push('myWidget_myCKEditor');
CKEditor_Init.push(function(){if(typeof CKEDITOR.instances['myWidget_myCKEditor']!='undefined' || !document.getElementById('myWidget_myCKEditor')) return;CKEDITOR.replace('myWidget_myCKEditor',{"htmlEncodeOutput" : true}); });
//]]>
</script>
</form>
....
All the evidence suggests that I am invoking the startup script at the wrong time, but I don't know when the "right time" to invoke it is.
Yoy can use jquery windows.ready function as below
insertScript = "<script type=""text/javascript""> <script language="javascript">
$(document).ready(function() {
window.CKEDITOR.instances.myWidget_myCKEditor.insertText('test');
})
})
</script> ";
Dim cManager As ClientScriptManager = Parent.Page.ClientScript
cManager.RegisterStartupScript(Me.GetType, "insertText", insertScript)
It will make sure your javascript fires only when document get ready and not b4 that.
Kind of a cop-out, but I ended up loading what I needed to insert on the page load and defining the script in the .ascx file.
In my myWidget.ascx:
<script type="text/javascript">
function ddChange(obj) {
window.CKEDITOR.instances.myWidget_myCKEditor.insertText(obj.value);
document.getElementById("myWidget_myCannedPicker").selectedIndex = 0;
}
</script>
...
<asp:DropDownList ID="myCannedPicker" Width="400" runat="server" AutoPostBack="false" OnChange="ddChange(this)" /></span></td>
In myWidget.ascx.vb:
Private Sub fillInitialValues()
...
myCannedPicker.DataSource = dt
myCannedPicker.DataValueField = "msg_text"
myCannedPicker.DataTextField = "msg_name"
myCannedPicker.DataBind()
myCannedPicker.Items.Insert(0, New ListItem("Please make a selection:", "0"))
End Sub
Doesn't really answer to the original question, but it was a suitable workaround in my case.
Related
I'm using webcam.js to get photos from a webcam using asp.net web form app. The problem is, I want to get the filename based on the "ID" querystring. But everytime I click "shoot" button, the querystring value is nothing.
Here's my complete HTML :
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Coba.aspx.vb" Inherits="myWebcam.Coba" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='<%=ResolveUrl("~/Plugin/jquery.webcam.js")%>' type="text/javascript"></script>
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
$(function (){
$("#Camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: '<%=ResolveUrl("Plugin/jscam.swf")%>',
onTick: function () { },
onSave: function () {
},
onCapture: function () {
webcam.save(pageUrl);
},
debug: function () { },
onLoad: function () { }
});
});
function Capture() {
webcam.capture();
return false;
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Index</h2>
<input type="button" value="Shoot!" onclick="Capture()" />
<div id="Camera"></div>
</div>
</form>
</body>
</html>
And here is my asp.net codebehind :
Imports System.IO
Imports System.Web.Services
Public Class Coba
Inherits System.Web.UI.Page
Public sID As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
sID = Request.QueryString("id")
If Not Page.IsPostBack Then
Capture(Trim(sID))
End If
End Sub
Public Sub Capture(ByVal mID As String)
Dim stream = Request.InputStream
Dim dump As String
If stream.Length > 0 Then
Using reader = New StreamReader(stream)
dump = reader.ReadToEnd()
End Using
Dim path = Server.MapPath("~/" & Trim(mID) & ".jpg")
System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump))
End If
End Sub
Private Function String_To_Bytes2(strInput As String) As Byte()
Dim numBytes As Integer = (strInput.Length) / 2
Dim bytes As Byte() = New Byte(numBytes - 1) {}
For x As Integer = 0 To numBytes - 1
bytes(x) = Convert.ToByte(strInput.Substring(x * 2, 2), 16)
Next
Return bytes
End Function
End Class
The first time I run the page, I can get the "id" value from the querystring. The shoot button trigger the postback and run the "Capture" sub but the "id" querystring returns nothing.
Any solutions for this problem ?
I tried the code and I think there is a mistake concept. The plugin does not seem to append any QueryString. Your ID is always Nothing. I made debugging and found no trace of the addition ID in the QueryString.
The file name is an attribute that you assign yourself with your logic.
Here is a complete example in which the ID is not recovered.
Even in the official page of the plugin there is no reference to the ID through Querystring.
Other things, you should not use the same page for the interface and saving process. The Pageload is always called, and you call Capture(Trim(sID)) even when loads the interface.
I think you must change this line:
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
In
var pageUrl = '<%=ResolveUrl("~/Coba_SaveImage.aspx")%>';
And all your codebehind go in the page Coba_SaveImage.aspx. In Page Load is not necessary the If Not Page.IsPostBack Then is always a postback.
Hope this help you.
I am updating an ASP.NET web site the Framework is 2.0. It is written in VB. I create a dropdown list and populate it dynamically. That is working. I need to add an event, onselectchange() to the dropdown. This event will change menu items.
This is the method creates the dropdown and populates it:
Public Sub ListLocations()
Dim facilityValueSelected As String = ""
'Get all of the facility service types from the database
'The stored procedure is ordered by ID.
GetServiceTypes()
Response.Write("<div style='text-align:left;'>")
Response.Write("<label>Facility Type:<select id='FacilityTypeDDL' name='FacilityTypeDDL' size='1' runat='server'>")
For Each facility As ListItem In lstBoxFacilityTypes
'Get the first value in the list and use the ID to to the list of locations below
If String.Compare(facilityValueSelected, "") = 0 Then
facilityValueSelected = facility.Value
End If
Response.Write("<option value=''" & facility.Value & "''>" & facility.Text & "</option>")
Next
Response.Write("</select></label>")
Response.Write("</div>")
End Sub
How do I add an event to this dropdownList when the user changes selections? I want the event to be handled in the code-behind so I can make a call to the database.
UPDATE
I added the 'onchange' event to the dropdown but it is not firing in the code behind. This is my changes:
Response.Write("<label>Facility Type:<select id='FacilityTypeDDL' name='FacilityTypeDDL' size='1' runat='server' onchange='UpdateLocationList()' autopostback='true'>")
This is the method I added to the code behind:
I put a breakpoint in this method at the event does not fire.
Public Sub UpdateLocationList()
Dim strFacilityValue As String = ""
'Get selected Service Type
strFacilityValue = "3"
'Populate Menu List
End Sub
UPDATE
Added the function to the dropdown:
Response.Write("<label>Facility Type:<select id='FacilityTypeDDL' name='FacilityTypeDDL' size='1' onchange='UpdateLocationList();' autopostback='true'>")
Added the javascript function below in the aspx page. The alerts do not show when the selection is changed.
<script type="text/javascript">
function UpdateLocationList(obj) {
alert('In function');
var facilityValue = document.getElementById("FacilityTypeDDL").value;
alert(facilityValue);
__doPostBack('FacilityTypeDDL', facilityValue);
}
</script>
UPDATE
ASPX page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Locations.aspx.vb" Inherits="Editor_Locations" %>
<script type="text/javascript">
function UpdateLocationList(obj) {
alert('In function');
var facilityValue = document.getElementById("FacilityTypeDDL").value;
alert(facilityValue);
__doPostBack('FacilityTypeDDL', facilityValue);
}
</script>
<%ListLocations()%>
UPDATE
I am getting the error: ReferenceError: UpdateLocationList is not defined. This is my javascript code:
<head runat="server">
<title>Locations</title>
<meta http-equiv="Content-Language" content="en-us"/>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script src = "scripts/jquery-1.11.2.min.js" type = "text/javascript"></script>
<script type="text/javascript">
function UpdateLocationList(obj) {
alert('In function');
var facilityValue = document.getElementById("FacilityTypeDDL").value;
alert(facilityValue);
__doPostBack('FacilityTypeDDL', facilityValue);
}
</script>
</head>
<body>
<%ListLocations()%>
</body>
I moved the javascript function, UpdateLocationList(), to a separate .js file and it was triggered.
I am trying to make it that on page load in the code behind, I disable a button in the radmenu using javascript
If I run my javascript in the console window in the browser to test then the button will disable. so that proofs that the JavaScript works.
the error is : cant find object - $find('myRadMenu') and the name is correct, so it has something todo with when the radmenu is rendered so I tried a wrap my script in a document.ready but that also won't work
'' not working with document.ready
' Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' ClientScript.RegisterStartupScript(Me.GetType(), "test", "<script type='text/javascript'> $(document).ready(function(){$find('myRadMenu').findItemByText('MyButton').disable();}); </script>")
' End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Me.GetType(), "test", "<script type='text/javascript'> $find('myRadMenu').findItemByText('MyButton').disable(); </script>")
End Sub
Do you know how to disable a radmenu button from javascript that is called from the vb.net page load function.
It must be done this way as I have other javascript that needs to fire
Please try with the below code snippet.
JS
function DisabelMenu(MenuText) {
setTimeout(function () { SetSettingAfterSometime(MenuText) }, 100);
}
function SetSettingAfterSometime(MenuText) {
var menu = $find("<%=RadMenu1.ClientID%>");
menu.findItemByText(MenuText).disable();
}
CS
RegisterStartupScript(this, this.GetType(), "test123", "DisabelMenu('test2');", true);
If you get the null then increase the timeout delay.
I have a page that includes javascript which I only want to run under certain conditions. To do this I have placed the scripts into an asp:placeholder
This actually seems to work but when I run a debug on the page I get the following warning.
Element 'placeholder' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing.
If I move the placeholders into the body of the page the warning goes, but that means I'm left with scripts in the body which I also want to avoid. Does anyone have any hints on the best practice for this scenario?? thanks
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='scripts/pageLoadAnimations.js'></scr" & "ipt>"
me.Header.Controls.Add(lt)
End Sub
You can include JS file straight from code behind:
If (some condition is true) Then
Page.ClientScript.RegisterClientScriptInclude("jQuery", "jquery-version.js")
End If
A couple of ways which fit your needs are:
Firstly, you could change your <head> tag to <head id="header" runat="server"> then this allows you to dynamically add anything into it, e.g.
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='pathtojavascriptfile'></script>"
me.Header.Controls.Add(lt)
Or you could create a Public string on your page, then stick the javascript in this.
Public _JS as string
Page_Load
_JS = "alert('here');" ' Or what ever your javascript is
ASPX Page
<head>
<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript">
$().ready(function(){
<%=(me._JS) %>
});
</script>
</head>
You might consider looking into the ClientScriptManager. This will allow you to inject scripts into the header properly using whatever conditions you require.
Including Custom Client Script in ASP.NET Pages
ClientScriptManager Class
i want to use jquery ui auto complete plugin in asp.net.
this is my behind code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim locations As String() = New String() {"Las Vegas", "Los Angeles", "Tampa", "New York", "s", "sss"}
Dim jsArray As String = GetJSArrayForVBArray(locations)
Me.ClientScript.RegisterArrayDeclaration("usernames", jsArray)
End Sub
Private Function GetJSArrayForVBArray(ByVal vbArray As String()) As String
Dim myResult As New StringBuilder()
For Each item As String In vbArray
With myResult
.Append(",'" & item & "'")
End With
Next
If (myResult.Length > 0) Then
Return myResult.ToString().Substring(1)
Else
Return ""
End If
End Function
this is html code :
<script type="text/javascript">
$(function () {
var availableTags = new Array();
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
what is the problem?
it does not work.
when i filling array in aspx page it works but when i want to fill in behind code not.
thanks.
Try changing your JS to this:
<script type="text/javascript">
$(function () {
$("#tags").autocomplete({
source: usernames
});
});
</script>
If I'm guessing at your .Net code correctly, you're registering "usernames" as the javascript array, but trying to use the empty 'availableTags' as your autocomplete source.
Note: this may be completely off-base here - I haven't actually used ClientScript.RegisterArrayDeclaration or the jQuery autocomplete plugin in code I've written before.