Sam Khan Sam Khan - 1 year ago 63
Javascript Question

On page load call change events?

On page load I need to call change events for the drop down list. Currently what happens is in my Jquery code below when you select a value from the professions drop down list i.e. GP a Help text then below the drop down shows in a DIV area shows, however once you submit the form and if validation is thrown the help text goes from the view.

I need to call change events for the drop down list #profession but not exactly sure how to do this. Please advise

$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "@Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
$('#ProfHelpAlert').show(); ///////
$('#ProfHelpAlert').hide(); ///////

var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down

Answer Source

Try this:

$(document).ready(function() {