How to add table item in AjaxToolkit Html Editor? - asp.net

I have used AjaxToolkit HtmlEditor and want to add the capability adding table to it.
How to add Table Item in toolbar?
%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor" TagPrefix="cc1" %>
<cc1:Editor runat="server" Width="700px" Style="margin: 0px auto; direction: rtl;" ID="Editor" Height="500px" CssClass="ajax__htmleditor_editor_container"
/>
I have found an approach in following link but I can't add table Item.

This solution adds an "insert table button" to the AjaxControlToolKit's "Editor" control (functionality is modeled and similar to that in Microsoft Word).
Now, I'm not saying this is a great solution (or code for that matter), since I just quickly whipped it together -- but it should give you the solution you want, with a solid base to refactor, etc.
Use the following steps to accomplish this:
1.)Create a new class file (Extended_AjaxToolkitHtmlEditor.cs) in your App_Code folder (if the folder does not exist, create it) and paste the following code into it:
using System;
using System.Text;
using System.Web.UI.WebControls;
using AjaxControlToolkit.HTMLEditor;
using AjaxControlToolkit.HTMLEditor.ToolbarButton;
namespace Extended_AjaxToolkitHtmlEditor
{
public class Extended_AjaxToolkitHtmlEditor : Editor
{
protected override void FillTopToolbar()
{
base.FillTopToolbar();
TopToolbar.Buttons.Add(new AddHtmlTable_HtmlEditorToolbarButton());
}
}
public class AddHtmlTable_HtmlEditorToolbarButton : MethodButton
{
private const string _strHtmlTableBase64Image = #"iVBORw0KGgoAAAANSUhEUgAAABYAAAAUCAYAAACJfM0wAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAABMSURBVDhPY0xISPjPQAPABKWpDoaewQygMMYFNm/eDGVhAnxyIDOHXlCAk1twcDCUSx2wdu3a0TBGgNEwhoPRMAaDIRzGUDYVAQMDADlBXF6jlWZpAAAAAElFTkSuQmCC";
private string _strJavaScript;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CssClass += " HtmlEditorAddTable";
Attributes.Add("onclick", #"Extended_AjaxToolKitEditorControl.ShowTablePopUp();");
_strJavaScript = #"<script>
var Extended_AjaxToolKitEditorControl = {
hasBeenInitialized : false,
divMainTable : {},
divMainTable_ChildElements : [],
Initialize_Elements : function(){
Extended_AjaxToolKitEditorControl.hasBeenInitialized = true;
var imgTableButtonElement = document.getElementById('" + ClientID + #"');
var imgTableButtonElement_boundingRectangle = imgTableButtonElement.getBoundingClientRect();
var divChildTableElement_toClone = document.createElement('div');
var divSpacerElement = {};
Extended_AjaxToolKitEditorControl.divMainTable = document.createElement('div');
Extended_AjaxToolKitEditorControl.divMainTable.id = 'divAjaxToolKit_editorControlExtended_mainTable';
Extended_AjaxToolKitEditorControl.divMainTable.style.background = 'white';
Extended_AjaxToolKitEditorControl.divMainTable.style.border = '1px solid black';
Extended_AjaxToolKitEditorControl.divMainTable.style.position = 'absolute';
Extended_AjaxToolKitEditorControl.divMainTable.style.visibility = 'hidden';
Extended_AjaxToolKitEditorControl.divMainTable.style.width = '220px';
Extended_AjaxToolKitEditorControl.divMainTable.style.height = '185px';
Extended_AjaxToolKitEditorControl.divMainTable.style.top = (imgTableButtonElement_boundingRectangle.bottom + window.pageYOffset) + 'px';
Extended_AjaxToolKitEditorControl.divMainTable.style.left = (imgTableButtonElement_boundingRectangle.left + window.pageXOffset) + 'px';
Extended_AjaxToolKitEditorControl.divMainTable.style.right = (imgTableButtonElement_boundingRectangle.right + window.pageXOffset) + 'px';
Extended_AjaxToolKitEditorControl.divMainTable.onmouseleave = function() { Extended_AjaxToolKitEditorControl.HideTablePopUp(); };
divChildTableElement_toClone.style.width = '10px';
divChildTableElement_toClone.style.height = '10px';
divChildTableElement_toClone.style.background = 'white';
divChildTableElement_toClone.style.border = '1px solid black';
divChildTableElement_toClone.style.marginRight = '5px';
divChildTableElement_toClone.style.marginLeft = '5px';
divChildTableElement_toClone.style.marginTop = '5px';
divChildTableElement_toClone.style.marginBottom = '5px';
divChildTableElement_toClone.style.display = 'inline-block';
for (var i = 0; i < 8; i++){ Extended_AjaxToolKitEditorControl.divMainTable_ChildElements.push([divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true), divChildTableElement_toClone.cloneNode(true)]); }
for (var rowCounter in Extended_AjaxToolKitEditorControl.divMainTable_ChildElements){
for (var columnCounter in Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter]){
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].id = 'newDArr_' + rowCounter + '_' + columnCounter;
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].setAttribute('data-rowCounter', rowCounter);
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].setAttribute('data-columnCounter', columnCounter);
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].onclick = function(){ Extended_AjaxToolKitEditorControl.InsertHtmlTable(this.id); };
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].onmouseover = function(){ Extended_AjaxToolKitEditorControl.SelectElementsInPopup(this.id); };
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter].onmouseout = function(){ Extended_AjaxToolKitEditorControl.UnSelectElementsInPopup(this.id); };
Extended_AjaxToolKitEditorControl.divMainTable.appendChild(Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[rowCounter][columnCounter]);
}
divSpacerElement = document.createElement('div');
divSpacerElement.style.display = 'block';
divSpacerElement.style.height = '1px';
Extended_AjaxToolKitEditorControl.divMainTable.appendChild(divSpacerElement);
}
imgTableButtonElement.parentNode.appendChild(Extended_AjaxToolKitEditorControl.divMainTable);
},
SelectElementsInPopup : function(paramDivId){
var divParameter = document.getElementById(paramDivId);
var divAttributeParamRowCount = divParameter.getAttribute('data-rowCounter');
var divAttributeParamColumnCount = divParameter.getAttribute('data-columnCounter');
for (var i = 0; i <= divAttributeParamRowCount; i++){
for (var j = 0; j <= divAttributeParamColumnCount; j++){
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[i][j].style.background = 'yellow';
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[i][j].style.border = '1px solid black';
}
}
},
UnSelectElementsInPopup : function(paramDivId){
var divParameter = document.getElementById(paramDivId);
var divAttributeParamRowCount = divParameter.getAttribute('data-rowCounter');
var divAttributeParamColumnCount = divParameter.getAttribute('data-columnCounter');
for (var i = 0; i <= divAttributeParamRowCount; i++){
for (var j = 0; j <= divAttributeParamColumnCount; j++){
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[i][j].style.background = 'white';
Extended_AjaxToolKitEditorControl.divMainTable_ChildElements[i][j].style.border = '1px solid black';
}
}
},
InsertHtmlTable : function(paramDivId){
var tableElement = document.createElement('table');
tableElement.style.width = '250px';
tableElement.style.height = '200px';
tableElement.border = '1';
var tableRowElement = {};
var tableColumnElement = {};
var divParameter = document.getElementById(paramDivId);
var divAttributeParamRowCount = divParameter.getAttribute('data-rowCounter');
var divAttributeParamColumnCount = divParameter.getAttribute('data-columnCounter');
for (var i = 0; i <= divAttributeParamRowCount; i++){
tableRowElement = tableElement.insertRow(i);
for (var j = 0; j <= divAttributeParamColumnCount; j++){ tableColumnElement = tableRowElement.insertCell(j); }
}
var editPanelElement = document.getElementById('" + this.Parent.Parent.Parent.Parent.Parent.ClientID + #"').control.get_editPanel().get_modePanels()[0].insertHTML(tableElement.outerHTML);
},
HideTablePopUp : function(){
var divMainTableElement = document.getElementById('divAjaxToolKit_editorControlExtended_mainTable');
divMainTableElement.style.visibility = 'hidden';
},
ShowTablePopUp : function(){
if (Extended_AjaxToolKitEditorControl.hasBeenInitialized != true){ Extended_AjaxToolKitEditorControl.Initialize_Elements(); }
var divMainTableElement = document.getElementById('divAjaxToolKit_editorControlExtended_mainTable');
divMainTableElement.style.visibility = 'visible';
}
};
</script>";
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var literalNewCSS = new Literal();
var strbldrStyleElement = new StringBuilder();
strbldrStyleElement.AppendLine(#"<style>");
strbldrStyleElement.AppendLine(#".HtmlEditorAddTable");
strbldrStyleElement.AppendLine(#"{");
strbldrStyleElement.AppendLine(#" width:23px !important;");
strbldrStyleElement.AppendLine(#" height:21px !important;");
strbldrStyleElement.AppendLine(#" margin-left:2px !important;");
strbldrStyleElement.AppendLine(#" background-image: url(data:image/png;base64," + _strHtmlTableBase64Image + ");");
strbldrStyleElement.AppendLine(#" background-repeat: no-repeat;");
strbldrStyleElement.AppendLine(#"}");
strbldrStyleElement.AppendLine(#"</style>");
literalNewCSS.Text = strbldrStyleElement.ToString();
Page.Header.Controls.Add(literalNewCSS);
Page.RegisterClientScriptBlock("Register_Extended_AjaxToolKitEditorControlJS", _strJavaScript);
}
}
}
2.)Then in the ASPX page, that you want to use this control, add the following at top of the file:
<%# Register Namespace="Extended_AjaxToolkitHtmlEditor" TagPrefix="extendedEditor" %>
3.)Then finally in form element to the ASPX page add the control like so below:
<extendedEditor:Extended_AjaxToolkitHtmlEditor runat="server" />
Notes:
1.)Be careful of the "aspx.designer.cs" file of the page you are adding this control to (if you are using one) -- when you put an ID on this new control element, errors get thrown. However, if you simply remove the entry that gets added in, it will still work and remove the errors.
2.)This solution assumes you have the AjaxControlToolkit downloaded and added into your project/references already. You can download it at: http://ajaxcontroltoolkit.codeplex.com/

You can do it in Javascript with an external button
<script type="text/JavaScript">
function insertTable() {
var editor = $find("<%= myEditor.ClientID %>");
var editPanel = editor.get_editPanel();
var designMode = AjaxControlToolkit.HTMLEditor.ActiveModeType.Design;
if(editPanel.get_activeMode() == designMode) {
var designPanel = editPanel.get_modePanels()[designMode];
designPanel.insertHTML("<table><tr><td></td></tr></table>");
}
}
</script>
On the aspx page
<cc1:Editor runat="server" id="myEditor" />
<input type="button" value="Insert html table" onclick="insertTable();" />

Related

Script not running in google chrome

I have a page in aspx which uses the following code. The issue is that it fetches the values from SQL and put into boxes using internet explorer but not doing using chrome
var element = document.getElementById("ctl00$pagecontent$Flexibleselect_Reol$ctl01");
//alert(element);
//alert('<%=Flexibleselect_Reol.Controls[1].ClientID %>');
element.onchange = (function(onchange) {
return function(evt) {
// reference to event to pass argument properly
evt = evt || event;
// new code "injection"
var puselectobj = document.getElementById('ctl00$pagecontent$Flexibleselect_Reol$ctl01');
var paramVal = puselectobj.value;
// alert(paramVal);
var newUrl = updateURLParameter('ProcessUnit', paramVal);
theForm.action = newUrl;
if (onchange) {
onchange(evt);
}
}
})(element.onchange);
// alert(element.onchange);
function updateURLParameter(param, value) {
var url = theForm.action;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (i = 0; i < tempArray.length; i++) {
if (tempArray[i].split('=')[0] != param) {
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var paramVal = value;
var rows_txt = temp + "" + param + "=" + paramVal;
var querystr = "?" + newAdditionalURL + rows_txt;
return baseURL + querystr;
}
I am getting the following error when running in chrome
"Uncaught TypeError: Cannot read properties of null (reading 'onchange')"

I am trying to programmatically add images to a list/array and access them in a for each loop to change their source image

I have been trying to add images to an array and then access their properties to change their source image in a loop.
Detailed: I create a grid with a layout for each for each grid element, in that layout there is a GridImage, who's source folder is set to "ClosedFolder.png", when I click one of the layouts it should change the clicked layouts folder to "OpenFolder.png".
for (int eachCount = 0; eachCount <= MaxRows / MaxCols; eachCount++)
{
Selectedrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(80, GridUnitType.Absolute) });
for (int newCol = 0; newCol <= MaxCols; newCol++)
{
for (int newRow = 0; newRow <= MaxRows / MaxCols; newRow++)
{
if (folderIndex >= DirectoryArrayList.Count) { break; }
var folder = DirectoryArrayList[folderIndex];
var label = new Label()
{
Text = folder.Name,
FontSize = 12,
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center
};
var GridImage = new Image() { Source = "ClosedFolder.png", StyleId = "Image" };
var GridTap = new TapGestureRecognizer();
var Layout = new StackLayout() { StyleId = "StackContent" };
var folderSelection = _mainFolder + "/" + folder.Name;
GridTap.Tapped += async(object sender, EventArgs e) =>
{
FileHandler.CreateTextFiles(folderSelection, "File_" + FileID + ".txt");
files = FolderOptions.AddFilesToList(folderSelection);
lst.ItemsSource = files;
//foreach (Image img in ImageList) I know this i incorrect, just an example of what I think!
//{
// img.Source = "ClosedFolder.png";
//}
GridImage.Source = "OpenFolder.png"; // clicked layout gets its openfolder.png
};
Layout.Children.Add(label);
Layout.Children.Add(GridImage);
Layout.GestureRecognizers.Add(GridTap);
Selectedrid.Children.Add(Layout, newCol, newRow);
folderIndex += 1;
FileID += 1;
}
}
}
Not sure on the declaration of the array and how to implement it.
I added the following into my BasicGrid method ...
var GridImage = new Image() { Source = "ClosedFolder.png", StyleId = "Image" };
var ImageList = new List<Image>{};
ImageList.Add( GridImage );
for (var i = 0; i < ImageList.Count; i++)
{
var img = ImageList[i];
img.Source = "ClosedFolder.png";
} GridImage.Source = "OpenFolder.png"
Just adding to say that Jason's information is the most likely direction I will go in, but as I am still learning it will take me time and I dint want to keep this open while I do that :-)

PhantomJS order iframe

How can I get the iframes on the page? I want to get an external options(width, height, id, src) and inner HTML.
It's all I can get only if the iframes on the page are not dynamically added. If they are dynamically added, the order of the IFRAME in the DOM and in the frameid (switchToFrame(frameid)) differs, and I can not compare them.
HTML:
<iframe src="iframe.php?id=1"></iframe>
<iframe src="iframe.php?id=2"></iframe>
<div id="dynamic_iframe"></div>
<div id="dynamic_iframe2"></div>
<iframe src="iframe.php?id=3"></iframe>
<script>
var el = document.createElement("iframe");
el.src = 'iframe.php?id=21';
document.getElementById('dynamic_iframe').appendChild(el);
var el = document.createElement("iframe");
el.src = 'iframe.php?id=22';
document.getElementById('dynamic_iframe2').appendChild(el);
</script>
PhantomJS:
getAllIFramesFromPage = function(page){
return page.evaluate(function() {
var matches = document.querySelectorAll('iframe');
ifames = [];
for(var i = 0; i < matches.length; ++i){
ifames.push(matches[i].src);
}
return ifames;
});
};
out:
iframe.php?id=1
iframe.php?id=2
iframe.php?id=21
iframe.php?id=22
iframe.php?id=3
PhantomJS:
var cnt = page.framesCount;
for(var i = 0; i < cnt; i++){
page.switchToFrame(i);
console.log(page.framePlainText);
page.switchToMainFrame();
}
out:
1
2
3
21
22
I was able to get out of a problem like this:
When I pass all the iframe into the DOM I put in them hidden value
page.switchToMainFrame();
page.evaluate(function() {
var matches = document.querySelectorAll('iframe');
ifames = [];
for(var i = 0; i < matches.length; ++i){
var iframeWindow = matches[i].contentWindow || matches[i].contentDocument.parent;
var frmBody = iframeWindow.document.getElementsByTagName("body")[0].frame_id = i;
}
});
Already inside an iframe I can get this value as follows:
var cnt = this.page.framesCount;
for(var i = 0; i < cnt; i++){
page.switchToFrame(i);
frameIndex = this.page.evaluate(function() {
if (document.getElementsByTagName("body")[0].frame_id !== undefined){
return document.getElementsByTagName("body")[0].frame_id;
}
return false;
});
this.page.switchToParentFrame();
}

runtime generated Checkbox validation

I have panel in the asp.net webpage, and i m generating the checkbox at runtime..
i want to validate checkbox, required field validator when form submit.
here is my code:
cv = new CustomValidator();
cv.ID = "cv" + "_" + dt.Rows[0]["RefQueID"].ToString();
cv.ValidationGroup = "grp";
cv.Display = ValidatorDisplay.None;
cv.ErrorMessage = "- Question " + intQuestionNo.ToString();
cv.ClientValidationFunction = "chkCount";
cv.Attributes.Add("rfvid", cv.ID.ToString());
//this portion of code is for custom validation javascript function
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'> function chkCount(sender,args) { ");
sb.Append(" args.IsValid = GetChk(document.getElementById('ctl00_ContentPlaceHolder1_" + cbl.ID.ToString() + "'))");
sb.Append(" } </script>");
Page page = HttpContext.Current.Handler as Page;
page.RegisterStartupScript("_Check", sb.ToString());
and in my javascript function i return this:
function GetChk(chkbox, args) {
if (!isConfirmed) {
alert('hi');
var chkBoxList = document.getElementById(chkbox.ClientID);
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}
but i m not getting the value of the checkbox...
required value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116_0
Actual Value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_complete_stage_chk_confirm
pls help...
first get the runtime generated control into the codebehind file from class file.
and then secondly after getting the control property, we can validate the checbox list.
Get the control into codebehind file from class file.
CheckBoxList cbl = (CheckBoxList)pnlref.FindControl("cbl_116");
provide the javascript validation to the runtime generated checkbox list.
function GetChk(chkbox, args) {
if (!isConfirmed) {
var chkBoxList = document.getElementById('ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116');
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}

highlight matching text?

I have flex 4 and writing my own autocomplete component (based on the popupanchor) to search for different books. In the dropdown box, how can I highlight the text that matches? For instance, a user types in "ema" and the search returns "Pet Sematary"....I want to highlight the letters "ema" within "Pet Sematary"
Wrote auto-complete a week ago :) You need to use Spark text components and pass custom TextFlow to them:
private function init():void
{
var textFlow:TextFlow = new TextFlow();
var paragraph:ParagraphElement = new ParagraphElement();
textFlow.addChild(paragraph);
var elements:Vector.<FlowElement> = highlight("Pet Sematary", "Se");
var n:int = elements.length;
for (var i:int = 0; i < n; i++)
{
paragraph.addChild(elements[i]);
}
label.textFlow = textFlow;
}
private function highlight(text:String, query:String):Vector.<FlowElement>
{
var result:Vector.<FlowElement> = new Vector.<FlowElement>();
// since we need to compare ignore-case we can not use split()
// and have to collect indexes of "query" matches in "text"
var indexes:Vector.<int> = new Vector.<int>();
var index:int = 0;
var textLowerCase:String = text.toLocaleLowerCase();
var queryLowerCase:String = query.toLocaleLowerCase();
var queryLength:int = query.length;
while (true)
{
index = textLowerCase.indexOf(queryLowerCase, index);
if (index == -1)
break;
indexes.push(index);
index += queryLength;
}
// now add SpanElement for each part of text. E.g. if we have
// text="aBc" and query is "b" then we add "a" and "c" as simple
// span and "B" as highlighted span.
var backgroundColor:uint = 0xFFCC00;
var n:int = indexes.length;
if (n == 0) // no matches
{
addSpan(result, text);
}
else
{
var startIndex:int = 0;
for (var i:int = 0; i < n; i++)
{
if (startIndex != indexes[i])
addSpan(result, text.substring(startIndex, indexes[i]));
addSpan(result, text.substr(indexes[i], queryLength),
backgroundColor);
startIndex = indexes[i] + queryLength;
}
if (startIndex != text.length)
addSpan(result, text.substr(startIndex));
}
return result;
}
private function addSpan(vector:Vector.<FlowElement>, text:String,
backgroundColor:* = "transparent"):void
{
var span:SpanElement = new SpanElement();
span.text = text;
span.backgroundColor = backgroundColor;
vector.push(span);
}
MXML code:
<s:RichEditableText editable="false" multiline="false"
selectable="false" id="label"
horizontalCenter="0" verticalCenter="0"/>
P.S: If you will have troubles with popup taking focus - add it manually to the toolTipChildren:
systemManager.toolTipChildren.addChildAt(child, 0);

Resources