I have the following jQueryUI Dialog element.. I'm trying to make an AJAX call to populate the form when it launches.. I'm also using Ajax to load the actual form..
Problem happens when the populateForm method is invoked..
The Dialog disappears and the browser leaves my page when the $.getScript method is invoked..
any ideas?
I'm stuck!
DIALOG
$('#highValueSurvey').dialog({
autoOpen: false,
modal: true,
width: 900,
resizable: false,
open: function(event, ui) {
$("#highValueSurvey").load('/longstoryshort/forms/high.html');
$("#highValueSurvey").dialog('option', 'position', 'center');
populateForm('#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm');
},
buttons: {
'Submit': function() {
var path = $(this).data('link').href; // Get the stored result
doAjaxPost('#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm');
setCookie(highValueCookieName, -1, 1000);
window.location.href = path;
}
}
});
CLICK EVENT
$("a.clickHighValueAsset").click(function(e) {
cookie_value = getCookie(highValueCookieName);
if (cookie_value != -1) {
e.preventDefault();
e.stopImmediatePropagation();
$("#highValueSurvey")
.data('link', this)// bind the url from the HREF to the dialog UI for redirect later
.dialog('open');
}
else {
return true;
}
});
POPULATE METHOD
function populateForm(formName) {
if (typeof eMail != 'undefined') {
elqServlet = window.location.protocol + '//' + window.location.host + '/longstoryshort/forms/lookup.jsp?email=';
$.getScript(elqServlet + eMail, function() {
$(':input', '#' + formName).each(function() {
var field = '#' + this.name + '';
$(field).val(GetElqContentPersonalizationValue(this.name));
});
});
}
}
Wrap the populateForm() which is async.. And then call the window.href redirect within it's success callback!
Example:
'Submit': function() {
$.ajax({
type: "POST",
async: true,
url: $("#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm").attr('action'),
data: $("#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm").serialize()
});
setCookie(highValueCookieName, -1, 1000);
$(":button:contains('Submit')").hide();
$("#highValueSurvey").load('/longstoryshort/forms/confirmation.html');
$("#highValueSurvey").dialog({
close: function() {
var path = $(this).data('link').href; // Get the stored result
window.location.href = path;
}
});
}
Related
Not sure how to pass along a bool to my (working) C# method DeleteTestuser. I've Googled the heck out of this but mileage varies with all kinds of pitfalls, i.e. old information, bad syntax.
Rather than passing confirm as false, below, I need to return a bool if the user confirms the action. Thanks...
index.cshtml
<a href="#Url.Action("DeleteTestUser", "Home",
new {id = testUser.TestUserId, confirm = false})"
id="confirm-delete">
_layout.cshtml
<script type="text/javascript">
$(function () {
$('#dialog-modal').dialog(
{
title: 'Test User',
draggable: false,
resizeable: false,
closeOnEscape: true,
modal: true,
autoOpen: false,
buttons: {
'Yes': function () {
$(this).dialog('close');
confirmResult(true);
},
'No': function () {
$(this).dialog('close');
confirmResult(false);
}
}
});
$('#confirm-delete').click(function () {
$('#dialog-modal').dialog("open");
});
function confirmResult(result) { return result }
});
</script>
Basically, you're recreating your own confirm() with jQuery UI Dialog. I did this and here is a similar case: confirm form submit with jquery UI
Apply this to your scenario and you have something like:
$(function() {
function ui_confirm(message, callback) {
var dfd = $.Deferred();
var dialog = $("<div>", {
id: "confirm"
})
.html(message)
.appendTo($("body"))
.data("selection", false)
.dialog({
autoOpen: false,
resizable: false,
title: 'Confirm',
zIndex: 99999999,
modal: true,
buttons: [{
text: "Yes",
click: function() {
$(this).dialog("close");
dfd.resolve(true);
if ($.isFunction(callback)) {
callback.apply();
}
}
}, {
text: "No",
click: function() {
$(this).dialog("close");
dfd.resolve(false);
}
}],
close: function(event, ui) {
$('#confirm').remove();
}
});
dialog.dialog("open");
return dfd.promise();
}
function deleteUser(id){
// Code you will execute to delete a user or POST back.
}
$(".button").button();
$('.del').click(function(e) {
e.preventDefault();
// your code
$.when(ui_confirm("Are you sure?")).done(function(val) {
if (val) {
console.log("Delete User Confirmed.");
deleteUser($(this).attr("id"));
} else {
console.log("Do not delete user.");
}
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
John Smith Delete
You may be able to get away with just executing specific callbacks. That's up to you. This code can then also be used to pass along another function or to use with a prompt() like dialog.
Update
See: Using Url.Action in javascript
For example:
function deleteTestUser(uid, conf){
var url = '#Url.Action("DeleteTestUser", "Home", new {id=' + uid + ', confirm=' + conf + '})';
$.get(url, function(data){
console.log("User " + uid + " Deleted.");
});
}
I would use POST if possible.
function deleteTestUser(uid, conf){
$.post('#Url.Action("DeleteTestUser", "Home")', { id: uid, confirm: conf }, function(data){
console.log("User " + uid + " Deleted.");
});
}
I have several delete href on a page.
</i>
When a user clicks on this link I'm showing a jquery box to ask if he is sure to delete.
Until now everything is working fine, but I can't the window.location.href with the parameters from data-key to work. Some help would much appreciated.
I have followed this example: http://jsfiddle.net/yayh3/3/
<script>
$(".delete").click(
function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:170,
modal: true,
buttons: {
"Verwijder": function() {
var me = $(this),
data = me.data('key');
window.location.href = "pagina_delete.php?id_record="+data.param1+"&id_table="+data.param2+"&table="+data.param3+"&paginanaam="+data.param4+"&template="+data.param5+"&lang="+data.param6;
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
}
);
});
</script>
You need to capture the context of the clicked element.
Directly within the click event handler, you can store the current value of this (which will refer to the clicked element), and then you can use this variable within the nested dialog methods/options.
In this case, you would just use var data = $(self).data('key') within the dialog method.
$(".delete").click(function () {
var self = this;
$("#dialog-confirm").dialog({
resizable: false,
height: 170,
modal: true,
buttons: {
"Verwijder": function () {
var data = $(self).data('key');
window.location.href = "pagina_delete.php?id_record=" + data.param1 + "&id_table=" + data.param2 + "&table=" + data.param3 + "&paginanaam=" + data.param4 + "&template=" + data.param5 + "&lang=" + data.param6;
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
I am using this functionality to fill the JQuery UI with minimum length set to 2. This code works good when I try to select the list through mouse or through keyboard.
But once I publish my code through my virtual machine it does not work. Neither the minimum length works nor the mouse or keyboard selection works.
Please help me here.
function SPAutoComplete(request, response) {
//debugger;
$.ajax({
url: 'Contracts/SearchSpByNumber',
type: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
success: function (json) {
var i = 0;
i++;
// call autocomplete callback method with results
response($.map(json, function (item) {
return {
label: item.SP_NBR,
SPDesc: item.SP_DESC,
ID: item.ElementID
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
}
$("#SP1").autocomplete({
source: SPAutoComplete,
minLength: 2,
select: function (event, ui) {
// alert('you have selected ' + ui.item.name + ' ID: ' + ui.item.name);
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
_newDirty = true;
event.preventDefault();
return false;
},
change: function (event, ui) {
debugger;
if (ui.item != undefined || ui.item != null) {
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
event.preventDefault();
return false;
}
},
focus: function (event, ui) {
debugger;
$("#SP1").val(ui.item.value);
return false;
}
});
I am using a jquery ui autocomplete. when the user types in their own value, rather than selecting an item from the list, the textbox clears. This is ok (I don't want the user to be able to enter their own values) except if the user types in a value that does exist on the list.
I tried using the autoSelect plugin as detailed in this post, but it is not working - I added the plugin but when I type in a value that IS on the list and hit tab, I get the same results as before - the textbox clears.
Here is my autocomplete:
$(function () {
$('[id$="txtDocType').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/MyPage.aspx/myFunction",
data: "{'prefixText':'" + request.term.toLowerCase() + "', 'ddvId':'" + this.element.data('autocomplete') + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) { }
});
},
minlength: 1,
select: function (event, ui) {
$('#divOtherFields input[type=text], input[type=password]').prop("disabled", false).removeClass("disabled");
$('[id$="btnSaveNext"],[id$="btnSaveClose"]').prop("disabled", false);
$('[id$="txtReceiptDate"]').datepicker("setDate", new Date());
}
});
});
Here is the plugin:
(function( $ ) {
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).on( "blur", function( event ) {
var autocomplete = $( this ).data( "autocomplete" );
if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
autocomplete.widget().children( ".ui-menu-item" ).each(function() {
var item = $( this ).data( "item.autocomplete" );
if ( matcher.test( item.label || item.value || item ) ) {
autocomplete.selectedItem = item;
return false;
}
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
}
});
}( jQuery ));
I set a breakpoint in the plugin on this line - "$( ".ui-autocomplete-input" ).on( "blur", function( event )" and the breakpoint was hit, yet the code would not step through. When I set a breakpoint to this line - "var autocomplete = $( this ).data( "autocomplete" );" the breakpoint was NOT hit.
Any ideas? I am at my wits end with this.
I solved this by making a couple of tweaks to the autoSelect plugin. Here is the code that eventually worked for me:
$(".ui-autocomplete-input").bind("focusout", function (event) {
var autocomplete = $(this).data("ui-autocomplete");
if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
autocomplete.widget().children(".ui-menu-item").each(function () {
var item = $(this).data("ui-autocomplete-item");
if (matcher.test(item.label || item.value || item)) {
autocomplete.selectedItem = item;
return false;
}
});
if (autocomplete.selectedItem) {
autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
}
});
I used the focus event to set the first value to a hidden variable. The same hidden variable also got updated in the select event. And then this was the hidden variable which I posted to the ajax call.
Why I did not use focus to set the value in the autocomplete input box, was because doing so populated the autocomplete input box even while I was typing in this box.
focus: function (event, ui) {
if($("#streetid")) $("#streetid").val(ui.item.label); //this was my hidden variable
}
},
I am using the jQueryUI autocomplete, have used it many times before, but I now have a more complex requirement.
I have a variable amount of Autocomplete fields to setup, using a JSON datasource and want to use an $().each to set these up. The problem appears to be the data: property of the AJAX call is always defaulting to values the final Autocomplete I setup.
$('[id$=CheckMethod]').each(function(index) {
if ($(this).val() === 'List') {
fieldToSetup = ($(this).attr('id').replace('txt',''));
fieldToSetup = left(fieldToSetup,(fieldToSetup.length - 11));
alert(fieldToSetup);
$('#txt' + fieldToSetup + 'CodeRoom' + escape(inRoomID)).autocomplete({
source: function (request, response) {
var src,
arrayData;
src = 'AJAXCheckCode.asp?actionType=List&GUID=' + $('#txtGUID').val();
$.ajax({
url: src,
datatype: 'json',
data: 'inCode=' + request.term + '&inType=' + $(this).attr('id'),
success: function (outData) {
arrayData = $.parseJSON(outData);
response($.map(arrayData, function (item) {
var theLabel = (item.Notes.length > 0) ? item.TheCode + ' - ' + item.Notes : item.TheCode;
return {
label: theLabel,
value: item.TheCode
};
}));
}
});
},
minLength: 1,
open: function (event, ui) {
$(".ui-slider-handle ui-state-default ui-corner-all").hide();
$(".ui-autocomplete.ui-menu").width(400);
$(".ui-autocomplete.ui-menu").css('z-index', 1000);
},
close: function (event, ui) {
$(".ui-slider-handle ui-state-default ui-corner-all").show();
},
focus: function (event, ui) {
return false;
},
select: function (event, ui) {},
search: function (event, ui) {
}
});
}
});//each CheckMethod
This code results in the 1st Autocomplete field using the inType parameter from the last field setup.
I'd rather not code for a maximum of 4 x 6 Autocomplete fileds and am trying to create one function to setup all the fields, is this possible?
Therefore my AJAX URL for my 1st Autocomplete looks like this
http://foo.com/AJAXCheckCode.asp?actionType=List&GUID={838138D6-A329-40F1-924B-58965842ECF8}&inCode=es&inType=A3&_=1335875408670
when "inType" should actually be A2, not A3 which is the last item of the outer $.each()
Hope this makes some sense!
Solved in the end by adding a class to the text box and then using live() on any text box with the given class that hasn't been bound before...works a charm
$('.foo:not(.ui-autocomplete-input)').live('focus', function(){
var fieldToReSource = ($(this).attr('id').replace('txt',''));
fieldToReSource = left(fieldToReSource,(fieldToReSource.length - 5));
$(this).autocomplete({
source: function (request, response) {
var src,
arrayData;
src = 'AJAXCheckCode.asp?inType=' + fieldToReSource + '&actionType=List&GUID=' + $('#txtGUID').val();
$.ajax({
url: src,
datatype: 'json',
data: 'inCode=' + request.term,
success: function (outData) {
arrayData = $.parseJSON(outData);
response($.map(arrayData, function (item) {
var theLabel = (item.Notes.length > 0) ? item.TheCode + ' - ' + item.Notes : item.TheCode;
return {
label: theLabel,
value: item.TheCode
};
}));
}
});
},
minLength: 1,
open: function (event, ui) {
$(".ui-slider-handle ui-state-default ui-corner-all").hide();
$(".ui-autocomplete.ui-menu").width(400);
$(".ui-autocomplete.ui-menu").css('z-index', 1000);
},
close: function (event, ui) {
$(".ui-slider-handle ui-state-default ui-corner-all").show();
},
focus: function (event, ui) {
return false;
},
select: function (event, ui) {
},
search: function (event, ui) {
}
});
});