How I keep a text modified by JavaScript during an AJAX request? - javascript

I have a textbox with autopostback = true and I have a JavaScript function to validate it. The JavaScript function also does a little format when the value is OK, but when I call it from PageRequestManager add_beginRequest or add_initializeRequest, the value is changed after the process. How can I do this?
First I control the request:
try {
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
}
catch (e) { }
Then I have my handler calling the validation function and I pass the type of validation I want. then precallbackvalidation is my custom validation function and if there is an error, it will reject the partial postback, but if the validation it's OK, the validation function has already made some format inside my textbox which is lost after the postback.
function InitializeRequest(sender, args) {
if (typeof precallbackvalidation == 'function') {
if ($(args._postBackElement).attr("PreCallBackIndex") != null) {
if (!precallbackvalidation(args._postBackElement)) {
args.set_cancel(true);
}
}
}
}
I want to know how to format my text by JavaScript and not losing it after the postback.
<asp:textbox ID="txtRut" runat="server" MaxLength="13" size="13" Width="75px" TabIndex="1" AutoPostBack="true" PreCallBackIndex="rutcte" ></asp:textbox>
On my page I have the textbox with the attribute to trigger the validation, and the validation function.
function precallbackvalidation(obj) {
var index = $(obj).attr("PreCallBackIndex");
if ($(obj).length > 0) {
switch (index) {
case 'rutcte':
return ValidarTipo('rut', obj, true);
break;
case 'ptjegastos':
if (ValidarTipo('entero', obj)==false) {
if (ValidarTipo('real', obj)==false) {
return false;
}
}
return true;
break;
case 'ptjemargen':
if (ValidarTipo('entero', obj) == false) {
if (ValidarTipo('real', obj) == false) {
return false;
}
}
return true;
break;
case 'ptjeppm':
if (ValidarTipo('entero', obj) == false) {
if (ValidarTipo('real', obj) == false) {
return false;
}
}
return true;
break;
case 'ptjecomision':
if (ValidarTipo('entero', obj) == false) {
if (ValidarTipo('real', obj) == false) {
return false;
}
}
return true;
break;
default:
return true;
break;
}
}
else {
return true;
}
}
The ValidarTipo (or ValidateTypes in English) is a generic function in JavaScript which does the format for the 'rut' option; but that format is lost after the all process ends
When I write "19" inside the textbox, the JavaScript function format this text to "1-9", but then when the request process continues after the beginrequest or initializerequest, the AJAX process seems to clear the JavaScripts modifications and let my text back to "19"

Related

Disable an input after click and validation occurs

I'm trying to disable an input in a form, but only after validation of fields.
function valJomclAddForm() {
f = document.jomclForm;
document.formvalidator.setHandler('list', function (value) {
return (value != -1);
});
if (document.formvalidator.isValid(f)) {
if(document.getElementById('membership6') === null) {
return false;
}
jQuery('input#submit').val('Publishing...');
jQuery('input#submit').prop('disabled', true);
return true;
} else {
//alert
}
}
but when function gets here:
jQuery('input#submit').prop('disabled', true);
return true;
Function stops, change input value to "Publishing" but doesn't publish, doesn't get the "return true"
Unless I remove jQuery('input#submit').prop('disabled', true);then function return true and publish this...
Why does this not work?
Thanks a lot in advance!

Wait for the return of the loop on form submit

I have the code below, the form is needed to be validated before it can submit the form.
But the problem is, the form continues to submit without validating.
<form action='#' method='post' onsubmit='return validate();'>
function validate()
{
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
}
});
});
How to handle the return of a loop?
Dont submit the form once encountered return false on the loop.
try this:
function validate()
{
var passes = true;
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
passes = false;
}
}
});
return passes;
});
Do not use return.
$('#my-form').on('submit', function(event){
if (validate() === false) {
event.preventDefault(); // like return false;
}
});
For more information see jQuery submit docs.
Each function has it's own returned value, the default returned value is an undefined value. You should check the length of the invalid elements after the each loop and return a proper value, since you are using jQuery I'd suggest:
$('form').on('submit', function (event)
{
var $invalid = $(this)
.find(':input:not(:submit,:hidden), select, textarea')
.removeClass('redBox')
.addClass(function () {
return this.getAttribute('requiredz')
&& $.trim(this.value) === ''
? 'redBox'
: null;
}).filter('.redBox');
if ($invalid.length)
{
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
});

using getElementsByName to validate radio button

I'm attempting to validate whether a group of radio buttons is checked in order o validate a form.
function formValidator() {
var triedIt = document.getElementsByName('tried');
if(radioChecked(triedIt, "Please select") {
return true;
}
return false;
}
function radioChecked(elem, helperMsg) {
if(document.myform.tried.checked == 1) {
return true;
}
else {
alert(helperMsg);
elem.focus();
return false;
}
}
This returns the alert, but for some reason the form gets processed anyway. I'm wondering what I'm doing wrong... any help would be appreciated.
If you're wondering why I don't just use jquery etc... its unfortunately not an option. Thanks!
I think it's happening because document.getElementsByName('tried') returns array of elements. So, when you call elem.focus() it will throw error (because array haven't method focus) and js stops execution.
function formValidator(){
var triedIt = document.getElementsByName('tried');
if(radioChecked(triedIt, "Please select")){
return true;
}
return false;
}
function radioChecked(elem, helperMsg){
if(document.myform.tried.checked == 1) {
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
try this i think you skipped one closing bracket ) in if(radioChecked(triedIt, "Please select")) that`s why its happening

js/jquery - event.preventdefault doesn't seem to work in firefox

I have some code which was written by someone else, which is supposed to open a popup if a zipcode is not in the correct format and stop the page from being submitted. It works correctly in IE and chrome. But in firefox i get the popup, click ok, and then the page submits. Can someone look over the code and let me know what's being done incorrectly? Code pasted at the end of this message.
Thank you
<script type="text/javascript">
$(init);
function init() {
$('form').validate({
error_messages: {
},
failure: function (errors) {
//alert(errors);
$(".errMsg").show();
return false;
},
success: function () {
//alert('passed');
//return true;
}
});
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
}
function clearText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == mymsg) {
document.forms['form1'].elements[mybox].value = '';
document.forms['form1'].elements[mybox].style.color = '#000000';
}
}
function resetText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == '') {
document.forms['form1'].elements[mybox].value = mymsg;
document.forms['form1'].elements[mybox].style.color = '#C0C0C0';
}
}
function beginZipValidation() {
//alert('begin validation');
var zip = $('#<%= Zip.ClientID %>').val().replace(/ /g, '').toUpperCase();
var cID = $("#<%= ddlCountry.ClientID %> option:selected").val();
if (!zipCodeValidation(true, cID, zip)) {
return false;
}
//alert('true');
return true;
}
function zipCodeValidation(shouldValidateEmpty, countryID, zc) {
//alert('zipCodeValidation');
if (zc == '' || zc == 'POSTALCODE') {
if (!shouldValidateEmpty) {
return true;
}
}
else {
switch (countryID) {
case '226':
if (/^\d{5}(-\d{4})?$/.test(zc))
return true;
break;
case '38':
if (/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\ ?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/.test(zc))
return true;
break;
case '225':
if (/^(GIR 0AA|[A-PR-UWYZ]([0-9][0-9A-HJKPS-UW]?|[A-HK-Y][0-9][0-9ABEHMNPRV-Y]?)[0-9][ABD-HJLNP-UW-Z]{2})$/.test(zc))
return true;
break;
case '13':
if (/^(((2|8|9)\d{2})|((02|08|09)\d{2})|([1-9]\d{3}))$/.test(zc))
return true;
break;
}
}
alert('The postal code provided does not fit the format for the selected country. Please adjust and try again.');
if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
event.preventDefault();
return false;
}
It might be as simple as the selector being wrong:
Try changing this:
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Instead be a bit more verbose like:
var myButtonId = "<%= btnAdd.ClientID %>"; // Now you know what this evaluates to client-side
var btnSelector = "#" + myButtonId;
$(btnSelector).click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Are you using the standard tools like Firebug or Chrome Developer tools to debug? If so, throw a few console.log("myButtonId: " + myButtonId); statements in there!

Postback a page based on webmethods result

How can I post back to a page based on result of WebMethod ?
function AssignmentConditionsSaveAS_Clicked() {
var txtConditionName = $('input[id$="txtConditionName"]').val();
PageMethods.IsExistsSavedCondition(txtConditionName, OnSuccess, OnFailure);
return false;
}
function OnSuccess(result) {
if (result == 'true') {
if (confirm('A saved condition with that name already exists. Do you want to overwrite?')) {
return true;
// I want to post back the clicked button
// Can not use __dopostback, because its a control inside a user control
}
else {
return false;
}
}
else if (result == 'false') {
alert('Not Exist');
}
}
function OnFailure(error) {
alert(error);
}
OR
How can I do somehting like this:
__doPostBack($('input[id$="btnSaveAS"]'), '');
You just have to do this
__doPostBack($('input[id$="btnSaveAS"]').attr('name'), '');
If I understand you correctly, you just need to get the button and call the click() function to do the post back.

Categories