ajax.beginform onsucess updatetargetid hidden input - asp.net-mvc-2

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.

Related

Leaflet - How to add click event to button inside marker pop up in ionic app?

I am trying to add a click listener to a button in a leaftlet popup in my ionic app.
Here I am creating the map & displaying markers, also the method I want called when the header tag is clicked is also below:
makeCapitalMarkers(map: L.map): void {
let eventHandlerAssigned = false;
this.http.get(this.capitals).subscribe((res: any) => {
for (const c of res.features) {
const lat = c.geometry.coordinates[0];
const lon = c.geometry.coordinates[1];
let marker = L.marker([lon, lat]).bindPopup(`
<h4 class="link">Click me!</h4>
`);
marker.addTo(map);
}
});
map.on('popupopen', function () {
console.log('Popup Open')
if (!eventHandlerAssigned && document.querySelector('.link')) {
console.log('Inside if')
const link = document.querySelector('.link')
link.addEventListener('click', this.buttonClicked())
eventHandlerAssigned = true
}
})
}
buttonClicked(event) {
console.log('EXECUTED');
}
When I click this header, Popup Open & Inside if are printed in the console, so I know I'm getting inside the If statement, but for some reason the buttonClicked() function isn't being executed.
Can someone please tell me why this is the current behaviour?
I just ran into this issue like 2 hours ago. I'm not familiar with ionic, but hopefully this will help.
Create a variable that keeps track of whether or not the content of your popup has an event handler attached to it already. Then you can add an event listener to the map to listen for a popup to open with map.on('popupopen', function(){}). When that happens, the DOM content in the popup is rendered and available to grab with a querySelector or getElementById. So you can target that, and add an event listener to it. You'll have to also create an event for map.on('popupclose', () => {}), and inside that, remove the event listener from the dom node that you had attached it to.
You'd need to do this for every unique popup you create whose content you want to add an event listener to. But perhaps you can build a function that will do that for you. Here's an example:
const someMarker = L.marker(map.getCenter()).bindPopup(`
<h4 class="norwayLink">To Norway!</h4>
`)
someMarker.addTo(map)
function flyToNorway(){
map.flyTo([
47.57652571374621,
-27.333984375
],3,{animate: true, duration: 5})
someMarker.closePopup()
}
let eventHandlerAssigned = false
map.on('popupopen', function(){
if (!eventHandlerAssigned && document.querySelector('.norwayLink')){
const link = document.querySelector('.norwayLink')
link.addEventListener('click', flyToNorway)
eventHandlerAssigned = true
}
})
map.on('popupclose', function(){
document.querySelector('.norwayLink').removeEventListener('click', flyToNorway)
eventHandlerAssigned = false
})
This is how I targeted the popup content and added a link to it in the demo for my plugin.
So yes you can't do (click) event binding by just adding static HTML. One way to achieve what you want can be by adding listeners after this new dom element is added, see pseudo-code below:
makeCapitalMarkers(map: L.map): void {
marker.bindPopup(this.popUpService.makeCapitalPopup(c));
marker.addTo(map);
addListener();
}
makeCapitalPopup(data: any): string {
return `` +
`<div>Name: John</div>` +
`<div>Address: 5 ....</div>` +
`<br/><button id="myButton" type="button" class="btn btn-primary" >Click me!</button>`
}
addListener() {
document.getElementById('myButton').addEventListener('click', onClickMethod
}
Ideally with Angular, we should not directly be working with DOM, so if this approach above works you can refactor adding event listener via Renderer.
Also I am not familiar with Leaflet library - but for the above approach to work you need to account for any async methods (if any), so that you were calling getElementById only after such DOM element was successfully added to the DOM.

Stop window from closing in tinyMCE in onSubmit function

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.

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;
}
});

Staying on same page using Modal, Form Validation and Constant Contact Form Generator

I am a jQuery newbie and ma trying to use a modal to reveal a constant contact simple form generated by the form generator. I have applied jQuery.validate(), and the validation is working, but I don't know how to submit the form. If there is an action="signup/index.php" in the tag, i land on a new page.
The generated form uses action='signup/index.php' and this file calls for a new page location see file in Github. I commented those last lines out, but still am failing to make the form submit. I cannot see the new email in the Constant Contact email list.
This is my sumbmit handler
submitHandler: function() {
$('#signup').click(function(e) {
$.post('signup/index.php', $().serialize(), function(data) {
$('#output-div').html(data);
});
$('#form-message').fadeIn(300, function() {
$('#form-message').html('<p>Thank you for joining our list. Great offers coming soon.</p>')
});
$('#myModal').delay(1500).trigger('reveal:close');
});
}
solved it.
I had commented out the last several lines of the signup/index.php, including this line
if($postFields['request_type'] == 'ajax'){ $postFields["success_url"]=''; $postFields["failure_url"]=''; }
For some reason, that line is needed for form submittal success. Everything after that line is commented out, from
if ($return_code==201) {
to
</ol>
</p>'; }
}
and my jQuery is handling messages, errors and completion as such
submitHandler: function() {
$.post('/dev/rest/ccphp/signup/index.php', $("#ccsfg").serialize(), function(data) {
$('#results').html(data);
}).success(function() {
$('#ccsfg').html('<h4>Thank you for joining our list. Great offers coming soon.</h4>');
})
.error(function() {
$('#ccsfg').html('<h4>Oops! There was an error. Please try again. </h4>');
})
.complete(function() {
$('#myModal').delay(1500).trigger('reveal:close');
});
}

jquery disabled button not working with IE

In my code I disable the submit button with jquery and then do a check to enable it. It works fine but not in IE. Could some please help me out, Thanks
function checkPassword() {
$('input#password').mouseout(function(){
var password =$('#password').val();
//event.preventDefault();
//alert(password);
$.ajax({
type: "POST",
url: "ajax/pass.php",
cache: false,
datatype:"html",
data: "password="+ password,
success: function(msg){
if (msg) {
$('#feedbk').html(msg);
var name = $('#feedbk').text().length;
var valid = 'Valid Password.';
var n = valid.length
if (name == n) {
$('#submit').attr("disabled", false);
$('#feedbk').fadeOut(3000);
} else {
$('#submit').attr("disabled", true);
}
}
}
});
});
};
The solution is to use regular javascript
var el = document.getElementById(selectBoxCheckBoxOrButtonID);
el.removeAttribute('disabled');
I used straight JavaScript to sort out the problem
document.getElementById('selectBoxCheckBoxOrButtonID').removeAttribute('disabled');
Thanks #user843753 your solution work marvelously.
I am reiterating it here because I cannot comment at the moment and it looks so non- intuitive (What! not a jquery solution).
But why oh why is it not fixed in JQuery 1.6.2?
My original issues with IE include, re-enbled disable buttons, only be made visible on mouse-over.
In another case the re-enabled disabled buttons could not made visible with any user interaction.