I have a grid control that allows users to add a value into the grid.
It produces the following link for inserting a brand new item.
<a onclick="if(!$find('radGridHolidays_ctl00').insertItem()) return false;" id="radGridHolidays_ctl00_ctl02_ctl02_PerformInsertButton" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("radGridHolidays$ctl00$ctl02$ctl02$PerformInsertButton", "", true, "", "", false, true))'>Insert</a>
I have some custom jQuery code that validates textboxes before the submit. I am trying to prevent the link from submitting the __doPostBack, but my code isn’t working.
// if need be, move this to its own .js file
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
// Document loaded, let's register some validation
$(function() {
$('#holidayValidationDisplay').hide();
$('a#radGridHolidays_ctl00_ctl02_ctl02_PerformInsertButton').click(function(e) {
e.stopImmediatePropagation();
e.preventDefault();
var hasErrors = false;
// alert('You clicked me!');
var holidayName = $('#radGridHolidays_ctl00_ctl02_ctl02_validatorHolidayName').val().trim();
var holidayDate = $('#radGridHolidays_ctl00_ctl02_ctl02_RDIPHolidayDate_dateInput_text').val().trim();
if (holidayName.length == 0) {
hasErrors = true;
$('#holidayList').append('<li>You must provide a holiday name</li>');
}
if (holidayDate.length == 0) {
hasErrors = true;
$('#holidayList').append('<li>You must provide a holiday date</li>');
}
if (hasErrors) {
$('#holidayValidationDisplay').show();
return false;
}
});
});
but the link is still firing off when I don’t want the postback to occur if there are errors. I saw something about preventing it to work in an UpdatePanel, but I’m not sure that the solution there applies to my scenario.
If anyone has any ideas, I’m all “ears”.
I believe the issue you’re having is that the button has no knowledge if the form is valid or not. This is what I do:
Write a custom function that returns true or false based on some other value:
So in this example, if my terms checkbox is checked, then args.IsValid is true. Just go to the link properties and there should be a property called
OnClientClick. You would putisTermsChecked.In your specific case, you would probably want to use a variable. If jQuery comes up invalid, set that variable to false, and the custom validation function will reference that variable. Essentially if it’s true, the button will proceed, false, and it won’t.
EDIT: If you’re doing validation on each row, the issue that I see is if one row fails validation then my solution above will make all link buttons disabled until all validation on the grid has passed. You may want to forget the custom function and do this:
If the jQuery validation fails, then find the link button in that row and add an
OnClickattribute with the valuereturn falsethen if validation passes, remove that attribute.