How can I run a Jquery function bound to another selector?
I have a piece of Jquery code that does a whole bunch of validation on a field. I currently have this fired on .blur()
.
As this field can be pre-populated on load by the server, I want to run that validation at that point also, but I don't know how to call the .blur()
function which is bound to the control.
Here is my code, most of it cut-out for brevity...
$('#<%=txtCity.ClientID %>').blur(function () {
$('#txtCityLoader.loader').show();
if ($('#<%=txtCity.ClientID %>').val().length == 0) {
//chuck some errors
}
$.ajax({
type: "POST",
url: "~/AtomicService/Validation.asmx/DoesCityExist",
data: "{'country':'" + $('#<%=ddlCountry.ClientID%>').val() + "'}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
$('#txtCityLoader.loader').hide();
if (msg["d"].length > 0) {
var data = $.parseJSON(msg.d);
if (data.Response == 'True') {
//all is well, tick the box
} else {
//stuff and nonsense
}
} else {
//do some other stuff
}
},
error: function (msg) {
//do stuff
}
});
开发者_开发知识库 });
When the page loads and document.ready()
fires, I'd like to run this function - how do I do that?
Help appreciated.
You need to trigger the event that you bound your method to
$('#<%=txtCity.ClientID %>').blur()
or
$('#<%=txtCity.ClientID %>').trigger('blur');
Move the code in your blur function to a seperate method. eg:
//Call your function when the document is ready
$(document).ready(yourFunction);
//Call your function on text box blur
$('#<%=txtCity.ClientID %>').blur(yourfunction);
//Your function
function yourFunction()
{
//Add your existing blur method code and ajax call here
}
function validate () {
$('#txtCityLoader.loader').show();
if ($('#<%=txtCity.ClientID %>').val().length == 0) {
//chuck some errors
}
$.ajax({ ... });
}
$('#<%=txtCity.ClientID %>').blur(validate);
$(document).ready(validate);
精彩评论