jQuery Autocomplete losing text on AutoPostBack - asp.net

I have a jQuery Autocomplete field on an ASP.Net Webform and everything has been working great until now. I also have a DropDownList that I have a need to fire onSelectedIndexChanged with AutoPostBack.
When I changed my code to do the AutoPostBack, the text field that has the jQuery AutoComplete on it comes back blank. However, if I look at the source of the page, the text is in the text field. If I now post the form, the page will send back a blank field. My Google-Fu is weak on this one, as I could not come up with any workaround for it.
Has anyone had any issues like this with the Autocomplete field getting blanked out on an AutoPostBack, and how did you get around it?
I can post code if it's really necessary, but I'd need to sanitize a lot of it before I could due to company policy.

How is the autocomplete field being initialized? Is it being set to empty string either on page load from server or by the autocomplete jQuery plugin on document.ready?
If the source code for the plug-in is setting the textbox to empty string on document.ready then try the following:
// Store current textbox value in a var
var temp = $('#mytextbox').val();
// Initialize the autocomplete plugin (winging it on the syntax)
$('#mytextbox').autocomplete();
// Reset the value of the textbox.
$('#mytextbox').val(temp);

If you use jQuery Autocomplete plugin 1.1,
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
Add "autoPostBackSelection: false," in the options Ex:
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
autoPostBackSelection: false,
...
After, add this just before the "return true; at the end of the "selectCurrent() function.
if (options.autoPostBackSelection == true) {
__doPostBack($input.id, "");
}
Example:
function selectCurrent() {
...
if (options.autoPostBackSelection ==
true) {
__doPostBack($input.id, "");
}
return true;
}

Related

Validation for Kendo AutoComplete when user does not select the value

I want the validation for kendo AutoComplete when user does not select any value from AutoComplete Value that is populated.
For Little Bit background say I do have two controls one as Kendo AutoComplete and other is Input box if user types something in the AutoComplete the values is populated and he does not select any value and switch to next control it must give a validation message that please select the value from the AutoComplete.
and Also if the user type any string in the AutoComplete and Switch to next control it must also give the validation that "hey,this value is not in the AutoComplete" so that it must not save any other data other than AutoComplete datas that is being Populated.
Heres how your auto complete is defined
#(Html.Kendo().AutoComplete()
.Name("countries")
// etc.
On submit button click event
<script>
$("#btnSubmit").click(function(){
var autoCompleteValue = $("#countries").val();
if (autoCompleteValue == "" || autoCompleteValue == null){
return false; //cancels submit action
}
// else let submit go through
});
</script>
The null check is probably useless, cuz if it doesn't have a value it's usually equal to ""
The .val() solution did not work for me, because the .val() value of the control is still the text I entered (custom text, not any of the AutoComplete values), and that's wrong.
Solution is in preventing the custom input of Kendo AutoComplete. See this link:
Kendo UI - Prevent Custom User Input in the AutoComplete

ASP GridView to be updated automatically when ModalDialog is closed

I have a gridView with search and filtering options, it is listing document from SharePoint Library, when i click on the Document name i added a Modal popup to display Documents properties page, if i update Document's title for example and select save, the item is updated but the gridview is still showing the old title, i need to press Search again in order to refresh the values.
the code i use for model popup is:
<script type="text/javascript">
function openModal(url) {
var options = SP.UI.$create_DialogOptions();
options.url = url;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
// Dialog callback
function CloseCallback(result, target) {
if (result === SP.UI.DialogResult.OK) {
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
}
</script>
what should i do to refresh and bid gridview data when the popup is closed?
on the click of save button, make a serverside call to rebind the gridview. i.e
$(document).ready(function(){
$('id_of_save_button').click(function(){
//ajax call of serverside method to rebind the grid.
});
});
However with asp.net these things become little easy if you use modalPopupExtender that ships with asp.net
Hi for handling sharepoint save event using javascript u can use this function
function PreSaveAction()
{
// write your gride view data bind code
}

Active Index is not being persisted in jQuery accordion change event

I have an asp.net aspx page and on that page I have a hidden input field with and id of paneIndex. However, when I load the page, the alert shows index 1 which is correct on the first load, but if I open up pane 3 for example, the alert shows 1 still. Am I doing something wrong?
In a Custom.js file, I have the following code:
$(document).ready(function() {
$("#accordion").accordion({
active: 1,
collapsible: true,
autoHeight: false,
change: function(event, ui) {
var activeIndex = $("#accordion").accordion('option', 'active');
$("#paneIndex").val(activeIndex);
//alert(activeIndex);
}
});
});
In my server side button click, I have the following code:
string activeIndex = Request.Form["paneIndex"];
string script = string.Format(#"<script type=""text/javascript"">var paneIndex =
{0};</script>", activeIndex);
if(!ClientScript.IsStartupScriptRegistered("JSScript"))
ClientScript.RegisterStartupScript(this.GetType(),"JSScript", script);
I have just tested the jquery script locally here and it works fine for me without form submission / postback.
Therefore I assume your issue is related to the form submission / activeIndex variable not being set correctly.
If you use asp.net, do you need to submit the form instead of using postbacks?
I always try to do a postback to the server if possible instead of form submission.
If you use Visual Studio you could also try to set a breakpoint on the server-side code and investigate the Request.Forms collection contains the correct variables after submission.

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)
This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.
When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.
Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.
To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.
The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.
Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.
I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.
Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?
I've found this problem reported several other places, but they offer no solutions:
jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator
ASP.NET forums, bug with ValidatorOnChange() function
I had the same problem. Solved by using this function:
jQuery.fn.extend({
fire: function(evttype){
el = this.get(0);
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(evttype, false, false);
el.dispatchEvent(evt);
} else if (document.createEventObject) {
el.fireEvent('on' + evttype);
}
return this;
}
});
So my "onSelect" event handler to datepicker looks like:
if ($.browser.msie) {
datepickerOptions = $.extend(datepickerOptions, {
onSelect: function(){
$(this).fire("change").blur();
}
});
}
I solved the issue with a patch:
window.ValidatorHookupEvent = function(control, eventType, body) {
$(control).bind(eventType.slice(2), new Function("event", body));
};
Update: I've submitted the issue to MS (link).
From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.
My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.
I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.
Not the answer you're probably looking for.
If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation
Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.
This is an endemic problem with jQuery datepickers and ASP validation controls.
As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.
I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).
The bit that fails is
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
which throws an error when it tries to get a length for the undefined 'vals'.
I just added
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.
Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.
// Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
function ValidatorOnChange(event) {
if (!event) {
event = window.event;
}
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof (targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
var i;
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
This is how I solved a simlar issue.
Wrote an onSelect() handler for the datepicker.
link text
In that function, called __doPostBack('textboxcontrolid','').
This triggered a partial postback for the textbox to the server, which called the validators in turn.

Resources