I have got four buttons in my html.
- Create Airport
- Create City
- Create City Shortname
- Create Airport Shortname
All of the button will give ajax call to same page and below is the code written for one of the button.
$('#imgbtnCreateAirport').click(function (event)
{
if($('#hidtext').val()!= 'true')
{
var file = $('input[type=file]').val();
if (!file)
{
$('#lblCreateKeywordsError').html('Please select the excel file from top.');
event.preventDefault();
return;
}
else if (!file.match(/^.*\.xls[xm]?$/))
{
$('#lblCreateKeywordsError').html('Please select excel file only!');
event.preventDefault();
return;
}
else
{
$('#lblCreateKeywordsError').empty();
var strInput = "";
strInput = strInput + "?cck=CreateAirportKeys";
var serviceReq = "/TridionCustomPageWeb/Exceldata/excelupload.aspx";
$.ajax({
url: serviceReq + strInput,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonpCallback: "processcck",
beforeSend: function()
{
$("#hidtext").val('true');
$("#imgbtnCreateAirport").attr('src', 'images/processing.gif').attr('alt','Processing...');
},
success: function(data, textStatus, jqXHR)
{
$("#hidtext").val('false');
$("#imgbtnCreateAirport").attr('src', 'images/CreateAirport.jpeg');
if (data.result=="CreateAirportKeys")
{
alert("Valid")
}
else
{
alert("Invalid");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + "---" + errorThrown);
}
});
return false;
}
event.preventDefault();
return;
}
else
{
alert("Please wait till other process is completed!!");
event.preventDefault();
return;
}
});
Now in above other than two things all the code will be same for every button, and below are the two thing will be different
strInput = strInput + "?cck=CreateAirportKeys"; //here CreateAirportKeys part will be different in every button call
$("#imgbtnCreateAirport").attr('src', 'images/processing.gif').attr('alt','Processing...'); // here $("#imgbtnCreateAirport") will be different.
I tried to make jquery function. but I was not able to make because of ‘event.preventDefault();’ as I was not able to get it in function.
Please suggest how can I write a function which will have event.preventDefault(); as well parameters for above two fields.
Thanks.
You can make a function that contains all your logic that you can call from each event handler and pass it in the specific parts that are different:
And, then for each event handler, you can do this:
As you can see, each click event handler calls the common code and passes in the three parts that are different, the event object, the string and the id value. For the DOM object, you could probably also either just pass
thisif you wanted it to always be the actual object that was clicked on or you can obtain that object from theeventalso.