How to get elements added in html editor - html

I have an html editor (ckeditor) in my vb.net application. after the user adds controls(buttons, input, text...) in the editor, he clicks on a button. after clicking that button i want to take all the elements added from that html editor... is there any way i can do it? I can get the text as string, but is there a way i can "transform" that string into html and get all the tags/controls added? ]
I'm new at this so please, excuse my errors. Thank you!
this is the function fired after button click
'ckeditor ID = "TBHTMLText"
Protected Sub btnGetElements_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetElements.Click
dim textAddedByUser as string
textAddedByUser = TBHTMLText.Text
End Sub
this textAddedByUser is everything the user adds in the editor so I was thinking if i develop an algorithm that can help me take every single tag and get the ID of each control added... but I think there is an easier way to do it. If so help me please.

I don't know anything about vb.net but with JavaScript you might have a listener for CKEditor's "change" event. Or, if you wanted to get the content from an editor instance upon the triggering of some arbitrary event, you could use CKEditor's getData() method. This would give you the raw HTML.
Examples:
When an arbitrary event is fired:
var editor = $(e.currentTarget).ckeditorGet();
var data = editor.getData();
var el = editor.element.$;
Setting up a "change" listener for CKEditor instances:
$.each(CKEDITOR.instances, function(i, editor) {
editor.on("change", function(e) {
var data = e.sender.getData();
var el = editor.element.$;
...
});
});

Related

element.addEventListener not adding listener

So I have an array of strings that will turn into buttons,
//At start
function acceptSuggestion() {
console.log(`clicked`)
console.log(this.textContent);
}
//Else where
suggestions.couldBe.innerHTML = ``;
list.suggestions.forEach(function (item) {
let button = document.createElement(`button`);
button.textContent = item;
button.addEventListener(`click`, acceptSuggestion);//before append
button.style = `text-align:center; width:50%`;
suggestions.couldBe.appendChild(button);
button.addEventListener(`click`, acceptSuggestion);//after append
suggestions.couldBe.innerHTML+=`<br>`;
});
It creates the buttons fine
But clicking them does nothing.
Why is this? I know I have the event right cuz of this: https://www.w3schools.com/js/js_htmldom_eventlistener.asp
If it matters, I am using electron.js to create an webpage like application, and not a browser.
The reason this is happening is because of this line:
suggestions.couldBe.innerHTML+="<br>";
What is happening is your Browser element is generating all new fresh HTML each loop because of the += on the innerHTML.
Basically in pseudo code:
var temp = suggestions.couldBe.innerHTML + "<br>;
suggestions.couldBe.innerHTML = temp;
This causes your element that was added via the suggestions.couldBe.appendChild(button); to be converted to html, then re-parsed and all new elements created from HTML each iteration of the loop. Because your Button event handler was created in JS; it is lost when it recreated the button from the HTML version.
You want to do this either all via JS; not mixing it. So my suggestion would be to change this line:
suggestions.couldBe.innerHTML+="<br>";
to
suggestions.couldBe.appendChild(document.createElement('br'));

Click html button and enable button in Visual Basic

I'm new with Visual Basic and I have a simple app in visual basic using the WebBrowser component, the web page that is loaded has a button (html) and I would like to enable a button of visual basic when press that html button, I have no idea how to achieve this, I read that I can do this but not how, I searched here in SO and youtube but I didn't found what I'm looking for, can you help me to achieve this please?, thanks.
<button type="button" id="login">Login</button>
I can simplify that for you :), and its very easy.
What I am using is the following:
1- HTML page "Index.html" with one simple javascript function called "CheckStat" to change your buttons value.
2- Form with 1 Button, 1 WebBrowser and 1 Timer.
"Index.html"
<!DOCTYPE html>
<html>
<head>
<title>HTML - VB.NET</title>
<script>
function CheckStat(){
document.getElementById("login").innerHTML = "clicked";
}
</script>
</head>
<body>
<button type="button" id="login" onclick="CheckStat();">Login</button>
</body>
</html>
This is what I did from Visual Studio, first this is my code:
"Form1.vb"
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'I am using localhost, it's not required you can simply put your HTML file on your Desktop or you can get it from any website.
WebBrowser1.Url = New Uri("http://localhost/stackoverflow.com/AN03/index.html")
'Enalbe Timer
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
'Get that our HTML button, as you see i am using GetElementById("HTML BUTTON ID HERE")....
Dim loginbtn = WebBrowser1.Document.GetElementById("login")
If loginbtn.InnerHtml = "clicked" Then
'Disable what button you want to disable...
Button1.Enabled = False
'Change HTML text to something else because every 100 interval it checks again and again...
loginbtn.InnerHtml = "click me"
'This message box just shows you were clicked or not. you can simply remove it
MessageBox.Show("Clicked me is enabled")
End If
Catch ex As Exception
'for any problem, it shows this message box to the user and tells him/her what was wrong....
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Because you said i am new for VB.net, let me tell you what is going on. when you click on Button1 the WebBrowser will load that file for you, and also enables Timer1.
now browser loaded the page and timer1 run that code every 100 intervals 1 Sec = 1000 interval, first it searches for all Element from HTML page which its ID equals to "login" and it returns to the variable called "loginbtn".
then it checks for its value (The text or caption that appears on HTML button) if it's equal to "clicked" then it means user click the HTML button.
Then it disables Button (VB's Button), changes HTML'S Button value to "click me again" and shows message box...
For any problem, it shows this message box to the user and tells him/her what was wrong....
Yes you can do it, but i used timer because it check it every i.e 1 min or 1 hour or any time you set...I updated for you and i created this function please let me know if you don't understand it or anything else....
you can disable or remove your timer, add one button and add this simple code to it which i put it in Button2...
one more thing, if you see i create my function as a Private, so you can't called from any other form, or class, etc.
you can change it to Public so you can use it anywhere in your app.
How do i call it then? .
like this : Form1.CheckStatByid("login"). updated code is :
Dim _Stat As Boolean = False
Private Function CheckStatByid(ByVal htmlid)
' Check sended paramiter
' IF it has no value then we need to end our function,
' Else we can check its value...
If htmlid <> Nothing Then
Try
'Get that our HTML button, as you see i am using GetElementById("HTML BUTTON ID HERE")....
Dim loginbtn = WebBrowser1.Document.GetElementById(htmlid)
'Check loginbtn if it has a value or NOT
If loginbtn <> Nothing Then
If loginbtn.InnerHtml = "clicked" Then
'Change HTML text to 'click me again', but you can change it to anything else...
loginbtn.InnerHtml = "click me again"
_Stat = True
Else
'If we have some value (ID) returns from our HTML, but it doesn't match our ID which is "login"
MessageBox.Show("loginbtn variable has deffrent id OR button is not clicked yet. and we end the try...catch")
Exit Try
End If
Else
'We don't find any elements from our HTML page...
MessageBox.Show("loginbtn variable has no value. and we end the try...catch")
Exit Try
End If
Catch ex As Exception
'for any proble it shows this message box to user and tell him/her what was wrong....
MessageBox.Show(ex.Message)
End Try
Else
' We don't have any ID to check...
MessageBox.Show("Please recall the function with an ID...")
End If
' Retuen _Stat : if the IF statment was true then it returns TRUE, else it returns FASLE
Return _Stat
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' How to use our function? its easy
' check it with some value.
If CheckStatByid("login") = True Then
' User Clicked the HTML button, we can now disable our button or do any thing else...
Button1.Enabled = False
Else
' User doesn't clicked the button or any other stat has been returned from our function.
' Message box will show for any stat...
' if you like, you can simply remove those message box from function and put them here...
MessageBox.Show("HTML page is not loaded or user doesn't clicked...")
End If
End Sub
Hope you understand it. and I am sorry for any grammar or spelling error.
...

Open primefaces tagcloud links in a new window

I'm using primefaces tagcloud. But when i clicked on the links given on the tagcloud, it opened in that same window.But on clicking the tagcloud links it should open in a new window not on the same window.
I want a new window will open when i click on the tagcloud links.
Can anyone please help me about this topics ???
JavaScript solution:
One possible approach could be JavaScript:
<p:tagCloud model="#{tagCloudBean.model}" onclick="preventDefault(event)">
<p:ajax event="select" update="msg" listener="#{tagCloudBean.onSelect}" />
</p:tagCloud>
onclick triggers a JavaScript function which prevents the link from getting opened.
function preventDefault(e) {
e.preventDefault();
}
Also, by adding an ajax event you can call a listener in your managed bean.
public void onSelect(SelectEvent event) {
TagCloudItem item = (TagCloudItem) event.getObject();
String url = item.getUrl();
String script = "window.open('" + url + "');"
RequestContext.getCurrentInstance().execute(script);
}
There you can access the url of the TagCloudItem and execute a JavaScript statement which should open a new browser window.
This possible solution is untested, but just give it a try.

AJAX HTMLEditorExtender on postback tables don't display

I am currently using an Ajax tool; HTMLEditorExtender to turn a textbox into a WYSIWYG editor, in a C# ASP.NET project. On the initial page load I place a large amount of formated text and tables into the editor which appears fine; even the tables.
The data is loaded into an asp:panel and the items/display from the panel is what is actually loaded into the extender and displayed.
However, if I want to have a button that saves all of the data that is in the editor to a Session and after the button press still display everything in the WYSIWG editor on the page postback everything that loads in the the textbox is fine except for the tables. They come up with the tags. Is there anyway around this?
The code I am using to initially load the page is this:
ContentPlaceHolder cphMain = (ContentPlaceHolder)this.Master.FindControl("MainContent");
Panel pnlContent = (Panel)cphMain.FindControl("innerFrame");
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnlContent.RenderControl(hw);
txtPN.Text = sb.ToString();
pnlContent.Visible = false;
On the button click I am having this saved:
string strHTMLText = txtPN.Text;
Session["ProgressNoteHTML"] = strHTMLText;
And I am loading it on the postback like this:
txtPN.Text = (string)Session["ProgressNoteHTML"];
ContentPlaceHolder cphMain = (ContentPlaceHolder)this.Master.FindControl("MainContent");
Panel pnlContent = (Panel)cphMain.FindControl("innerFrame");
pnlContent.Visible = false;
Any ideas as to why any postbacks would make the tags appear and in the original page load they do not?
The solution offered by Erik won't work for table tags containing property values. For instance: <table align="right"> will not be decoded. I have also found that <img> tags are encoded by the HTMLEditorExtender as well.
The easier solution is to use the Server.HTMLDecode() method.
TextBox_Editor.Text = Server.HtmlDecode(TextBox_Editor.Text) 'fixes encoding bug in ajax:HTMLEditor
I have the same problem, It seems to have something to do with the default sanitizing that the extension performs on the HTML content. I haven't found a way to switch it off, but the workaround is pretty simple.
Write an Anti-Sanitizing function that replaces the cleansed tags with proper tags. Below is mine written in VB.Net. A C# version would look very similar:
Protected Function FixTableTags(ByVal input As String) As String
'find all the matching cleansed tags and replace them with correct tags.
Dim output As String = input
'replace Cleansed table tags.
output = output.Replace("<table>", "<table>")
output = output.Replace("</table>", "</table>")
output = output.Replace("<tbody>", "<tbody>")
output = output.Replace("</tbody>", "</tbody>")
output = output.Replace("<tr>", "<tr>")
output = output.Replace("<td>", "<td>")
output = output.Replace("</td>", "</td>")
output = output.Replace("</tr>", "</tr>")
Return output
End Function

call code behind functions with html controls

I have a simple function that I want to call in the code behind file name Move
and I was trying to see how this can be done and Im not using asp image button because not trying to use asp server side controls since they tend not to work well with ASP.net MVC..the way it is set up now it will look for a javascript function named Move but I want it to call a function named move in code behind of the same view
<img alt='move' id="Move" src="/Content/img/hPrevious.png" onclick="Move()"/>
protected void Move(){
}
//based on Search criteria update a new table
protected void Search(object sender EventArgs e)
{
for (int i = 0; i < data.Count; i++){
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell CheckCell = new HtmlTableCell();
HtmlTableCell firstCell = new HtmlTableCell();
HtmlTableCell SecondCell = new HtmlTableCell();
CheckBox Check = new CheckBox();
Check.ID = data[i].ID;
CheckCell.Controls.Add(Check);
lbl1.Text = data[i].Date;
lbl2.Text = data[i].Name;
row.Cells.Add(CheckCell);
row.Cells.Add(firstCell);
row.Cells.Add(SecondCell);
Table.Rows.Add(row);
}
}
Scott Guthrie has a very good example on how to do this using routing rules.
This would give you the ability to have the user navigate to a URL in the format /Search/[Query]/[PageNumber] like http://site/Search/Hippopotamus/3 and it would show page 3 of the search results for hippopotamus.
Then in your view just make the next button point to "http://site/Search/Hippopotamus/4", no javascript required.
Of course if you wanted to use javascript you could do something like this:
function Move() {
var href = 'http://blah/Search/Hippopotamus/2';
var slashPos = href.lastIndexOf('/');
var page = parseInt(href.substring(slashPos + 1, href.length));
href = href.substring(0, slashPos + 1);
window.location = href + (++page);
}
But that is much more convoluted than just incrementing the page number parameter in the controller and setting the URL of the next button.
You cannot do postbacks or call anything in a view from JavaScript in an ASP.NET MVC application. Anything you want to call from JavaScript must be an action on a controller. It's hard to say more without having more details about what you're trying to do, but if you want to call some method "Move" in your web application from JavaScript, then "Move" must be an action on a controller.
Based on comments, I'm going to update this answer with a more complete description of how you might implement what I understand as the problem described in the question. However, there's quite a bit of information missing from the question so I'm speculating here. Hopefully, the general idea will get through, even if some of the details do not match TStamper's exact code.
Let's start with a Controller action:
public ActionResult ShowMyPage();
{
return View();
}
Now I know that I want to re-display this page, and do so using an argument passed from a JavaScript function in the page. Since I'll be displaying the same page again, I'll just alter the action to take an argument. String arguments are nullable, so I can continue to do the initial display of the page as I always have, without having to worry about specifying some kind of default value for the argument. Here's the new version:
public ActionResult ShowMyPage(string searchQuery);
{
ViewData["SearchQuery"] = searchQuery;
return View();
}
Now I need to call this page again in JavaScript. So I use the same URL I used to display the page initially, but I append a query string parameter with the table name:
http://example.com/MyControllerName/ShowMyPage?searchQuery=tableName
Finally, in my aspx I can call a code behind function, passing the searchQuery from the view data. Once again, I have strong reservations about using code behind in an MVC application, but this will work.
How to call a code-behind function in aspx:
<% Search(ViewData["searchQuery"]); %>
I've changed the arguments. Since you're not handling an event (with a few exceptions, such as Page_Load, there aren't any in MVC), the Search function doesn't need the signature of an event handler. But I did add the "tablename" argument so that you can pass that from the aspx.
Once more, I'll express my reservations about doing this in code behind. It strikes me that you are trying to use standard ASP.NET techniques inside of the MVC framework, when MVC works differently. I'd strongly suggest going through the MVC tutorials to see examples of more standard ways of doing this sort of thing.