Stop window from closing in tinyMCE in onSubmit function - tinymce

I am trying to add some validation logic to the code plugin for tinyMCE.
It seems, however, that when a window's onSubmit function is called, the window closes by default.
The onSubmit function currently looks like this:
onSubmit: function (e) {
// We get a lovely "Wrong document" error in IE 11 if we
// don't move the focus to the editor before creating an undo
editor.focus();
editor.undoManager.transact(function () {
editor.setContent(e.data.code);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
}
What I would like to do is add some validation logic to the plugin to prevent tinyMCE from reformatting invalid html and, rather, display a message that the html is invalid. Essentially, something like this:
onSubmit: function (e) {
// We get a lovely "Wrong document" error in IE 11 if we
// don't move the focus to the editor before creating an undo
var isCodeValid = true;
//check if code valid
isCodeValid = ValidateCode(e.data.code);
if (isCodeValid) {
//if code valid, send to tinyMCE to let it do it's thing
editor.focus();
editor.undoManager.transact(function () {
editor.setContent(e.data.code);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
}
else {
//if code invalid, display error message and keep text editor window open
tinyMCE.activeEditor.windowManager.alert("Your HTML is invalid. Please check your code and try submitting again.");
return;
}
}
However, it seems that the onSubmit function closes the text editor window regardless. I was wondering if there is a way to stop it from doing this. I have scoured the documentation which leaves much to be explained and have looked at other plugins as examples. The closest I can find is the searchandreplce plugin. The 'Find' button calls the onSubmit function, but it seems to stay open if the 'find' text field is blank. However, the logic behind it seems very different from what I can use in the Code plugin as it is.
Can anyone who is familiar with the tinyMCE API give me any ideas on how to prevent the window from closing when onSubmit is called? Or do I have to go another route?

As per this question the way to cancel an event is to return false;. This will keep the popup open. Your code would then become:
onSubmit: function (e) {
// We get a lovely "Wrong document" error in IE 11 if we
// don't move the focus to the editor before creating an undo
var isCodeValid = true;
//check if code valid
isCodeValid = ValidateCode(e.data.code);
if (isCodeValid) {
//if code valid, send to tinyMCE to let it do it's thing
editor.focus();
editor.undoManager.transact(function () {
editor.setContent(e.data.code);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
}
else {
//if code invalid, display error message and keep text editor window open
tinyMCE.activeEditor.windowManager.alert("Your HTML is invalid. Please check your code and try submitting again.");
return false;
}
}

I figured it out finally. All you need to do is add e.preventDefault(); at the start of the onSubmit function and the window will not close. The documentation was no help, but looking at the searchandreplace plugin as an example lead me to the answer. What I have now is like this:
onSubmit: function (e) {
e.preventDefault();
// We get a lovely "Wrong document" error in IE 11 if we
// don't move the focus to the editor before creating an undo
var isCodeValid = true;
//check if code valid
isCodeValid = ValidateCode(e.data.code);
if (isCodeValid) {
//if code valid, send to tinyMCE to let it do it's thing
editor.focus();
editor.undoManager.transact(function () {
editor.setContent(e.data.code);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
}
else {
//if code invalid, display error message and keep text editor window open
tinyMCE.activeEditor.windowManager.alert("Your HTML is invalid. Please check your code and try submitting again.");
return;
}
}
e.PreventDefault() seems to stop the default behavior of the onSubmit function.

Related

How to detect Google places AutoComplete load issues?

I'm using the API successfully but encountered an error this morning with "OOPS! Something went wrong" sitting in the textbox and the user cannot type into it. I found the issue to be key related and fixed, however, this brought to light that some issue may arise and the user cannot complete because of this blocking. I'd like to be able to detect in javascript if there is some issue with the google.maps.places.Autocomplete object and not bind it to the textbox.
For anyone else wanting to do this.
Thanks to the folks for the idea over at:
Capturing javascript console.log?
// error filter to capture the google error
(function () {
var oldError = console.error;
console.error = function (message) {
if (message.toLowerCase().includes("google maps api error")) {
document.getElementById('<%=hdnGoogleSelected.ClientID %>').value = "DISABLE";
triggerUpdatePanel();
//alert(message);
}
oldError.apply(console, arguments);
};
})();
Mine is in an update panel so I triggered the update which sets the onfocus back to this.select(); for the textbox which effectively disables the autocomplete attempts.
tbAddress1.Attributes["onfocus"] = "javascript:this.select();";
Another option:
Google will return an error after about 5 seconds from loading.
"gm-err-autocomplete" class indicates any error with the autocomplete component.
You can periodically check for the error class google returns. I do it for 10 seconds after loading:
function checkForGoogleApiErrors() {
var secCounter = 0;
var googleErrorCheckinterval = setInterval(function () {
if (document.getElementById("AddressAutocomplete").classList.contains("gm-err-autocomplete")) {
console.log("error detected");
clearInterval(googleErrorCheckinterval);
}
secCounter++;
if (secCounter === 10){
clearInterval(googleErrorCheckinterval);
}
}, 1000);
}

bootstrap-validator check form

I am using 1000hz BootstrapValidator and after click on button (not submit because I need to stay on page without refresh) I want to check if form is correct.
I just can call $("#form2").validator('validate'); but I am not able to get return value.
I know about isDefaultPrevented but it is called after submit and I do not want submit.
$('#form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
}
})
Yeah one way is to change the from submit button type from submit to buttonand handle the validation via click function and count the length if any input field has error ($('#form2').validator('validate').has('.has-error').length) and handle it with if/else condition.
$(document).ready(function(){
$("#myButton").click(function() {
if ($('#form2').validator('validate').has('.has-error').length) {
alert('SOMETHING WRONG');
} else {
//$("#form2").submit();
alert('EVERYTHING IS GOOD');
}
});
});
Fiddle Example

Change content before preview in TinyMCE 4

In TinyMCE 4, I want to change displayed contents before they are showed on preview popup windows. This change must not affect current contents in editor. Can we do that?
If it can't, I want to catch close event of preview windows. How to do that?
TinyMCE allows us to register callbacks via the property init_instance_callback
By using the BeforeExecCommand event, oddly not in current documentation, you can make changes prior to a command being executed. We can similarly use the ExecCommand event to make changes after the command is executed. The Preview Plugin triggers the mcePreview command. You can view the Editor command Identifiers here.
Putting that together you can add the following when initializing your TinyMCE. This will show "changed content" in the preview without making visible changes to the content within TinyMCE.
var preProssesInnerHtml;
tinymce.init({
//other things...
init_instance_callback: function (editor) {
editor.on('BeforeExecCommand', function (e) {
if (e.command == "mcePreview") {
//store content prior to changing.
preProssesInnerHtml = editor.getContent();
editor.setContent("changed content");
}
});
editor.on("ExecCommand", function (e) {
if (e.command == "mcePreview") {
//Restore initial content.
editor.setContent(preProssesInnerHtml);
}
});
}
}

How to fire place_changed event for Google places auto-complete on Enter key

The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.
function locationAuto() {
$('.search-location').focus(function () {
autocomplete = new google.maps.places.Autocomplete(this);
searchbox = this;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var thisplace = autocomplete.getPlace();
if (thisplace.geometry.location != null) {
$.cookie.raw = true;
$.cookie('location', searchbox.value, { expires: 1 });
$.cookie('geo', thisplace.geometry.location, { expires: 1 });
}
});
});
The .search-location is a class on multiple textboxes.
There is a submit button that takes the values from the cookies and redirects (server side)
Adapted from Jonathan Caulfield's answer:
$('.search-location').keypress(function(e) {
if (e.which == 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
return false;
}
});
I've encountered this problem as well, and came up with a good solution. In my website I wanted to save the autocomplete.getPlace().formatted_address in a hidden input prior to submission. This worked as expected when clicking the form's submit button, but not when pressing the Enter key on the selection in the autocomplete's dropdown menu. My solution was as follows:
$(document).ready(function() {
// Empty the value on page load
$("#formattedAddress").val("");
// variable to indicate whether or not enter has been pressed on the input
var enterPressedInForm = false;
var input = document.getElementById("inputName");
var options = {
componentRestrictions: {country: 'uk'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$("#formName").submit(function(e) {
// Only submit the form if information has been stored in our hidden input
return $("#formattedAddress").val().length > 0;
});
$("#inputName").bind("keypress", function(e) {
if(e.keyCode == 13) {
// Note that simply triggering the 'place_changed' event in here would not suffice, as this would just create an object with the name as typed in the input field, and no other information, as that has still not been retrieved at this point.
// We change this variable to indicate that enter has been pressed in our input field
enterPressedInForm = true;
}
});
// This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined, and the next time it has the data. This is why the following logic has been added.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// If getPlace() is not undefined (so if it exists), store the formatted_address (or whatever data is relevant to you) in the hidden input.
if(autocomplete.getPlace() !== undefined) {
$("#formattedAddress").val(autocomplete.getPlace().formatted_address);
}
// If enter has been pressed, submit the form.
if(enterPressedInForm) {
$("#formName").submit();
}
});
});
This solution seems to work well.
Both of the above responses are good answers for the general question of firing a question when the user presses "enter." However - I ran into a more specific problem when using Google Places Autocomplete, which might have been part of the OP's problem. For the place_changed event to do anything useful, the user needs to have selected one of the autocomplete options. If you just trigger 'place_changed', the if () block is skipped and the cookie isn't set.
There's a very good answer to the second part of the question here:
https://stackoverflow.com/a/11703018/1314762
NOTE: amirnissim's answer, not the chosen answer, is the one to use for reasons you'll run into if you have more than one autocomplete input on the same page.
Maybe not the most user friendly solution but you could use JQuery to disable the enter key press.
Something like this...
$('.search-location').keypress(function(e) {
if (e.which == 13) {
return false;
}
});

ajax.beginform onsucess updatetargetid hidden input

I am trying to call a jquery ui dialog by attaching the function to the onsuccess property of the ajaxoptions on a ajax.beginform..
<script type="text/javascript">
// Dialog
$(document).ready(function () {
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
"Ok": function () {
$(this).dialog("close");
}
}
});
});
</script>
In a seperate script file I have this..
function EmailResult() {
$('#dialog').dialog('open');
}
Then I have a contact form that is not actually wired up yet, the controller just responds with one of two string responses.
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "ContactResult", OnSuccess="EmailResult" }))
{ %>
If I take out the OnSuccess="EmailResult" from the Ajax.BeginForm or simply remove $('#dialog').dialog('open'); from my EmailResult function the error goes away so obvisouly this is an issue with the OnSuccess property and a Jquery UI Dialog.
My first question is am I doing something wrong that is causing this not to work and/or if this won't work then is there a better solution.
I am trying to create a dialog that comes up and says whether the message was sent. I do not want to use the alert dialog box.
I guess the error would help, in the IE 8 debugger it comes up with an undefined error in the MicrosoftAjax.js library
The finally block of this code is causing the problem and under the locals tab in IE 8 it says b is undefined.
this._onReadyStateChange = function () {
if (a._xmlHttpRequest.readyState === 4) {
try {
if (typeof a._xmlHttpRequest.status === "undefined") return
} catch (b) {
return
}
a._clearTimer();
a._responseAvailable = true;
try {
a._webRequest.completed(Sys.EventArgs.Empty)
} finally {
if (a._xmlHttpRequest != null) {
a._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
a._xmlHttpRequest = null
}
}
}
};
What it was updating was
<%= Html.Hidden("ContactResult") %>
Which turns out was the whole problem, I changed the Hidden Input to a div and it works perfectly. Not sure why but... if anyone else runs into this there you go...
So I guess this is what I figured out.. I started a new mvc project with two inputs and started just using an alert box as it turns out it was not related to the jquery.ui dialog plugin. I got it to work correctly with the alert box coming up after it was run using the ajax.beginform.
So long story short.. You can't use a Hidden Input for the UpdateTargetID in the Ajax.BeginForm? I guess this is kind of a question and the answer but changing the UpdateTargetID to the ID of a "div" fixed it and it works appropriately. You can even set the Div visibility to hidden and it works.