I'm using my code to fetch data from a server and show it with inputs and labels.
My only problem is that, when I enter the page the select change is not triggered therefore I don't get any data. The only way to make it work is select another option and select the same again so the change event is triggered. $('#selectMRPC').trigger('change'); doesn't help.
How can I make my selectorMRPC() and $('#selectMRPC').change be executed when the page loads?
$(document).ready(function () {
selectorMRPC();
$('#selectMRPC').trigger('change');
$('#selectMRPC').change(function () {
//fetch data
var mrpc = $(this).find('option:selected').data('mrpc');
$('#paramBody').empty();
for (var i = 1; i <= 10; i++) {
var field = mrpc["field" + i];
if (field !== undefined) {
var parsedField = field.split('_');
var value = parsedField[0];
var type = parsedField[1];
switch (type) {
case "S":
type = "text";
if (value === '""')
value = null;
break;
case "B":
type = "checkbox";
break;
case "N":
type = "number";
value = parseInt(value);
break;
case "D":
type = "number";
value = parseInt(value);
if (value === '""')
value = null;
break;
}
//else use checkbox
if(type === "checkbox")
{
$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><div class="checkbox checkbox-primary">' +
'<input class="text-center" id="field'+i+'" name="Fields" type="checkbox" value="' +value + '"><label for="field'+i+'"></label></div></tr>');
}
else
{
$('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input class="text-center" name="Fields" type="' + type + '" value="' +value + '"></tr>');
}
}
}
});
function selectorMRPC() {
$.ajax({
type: 'post',
url: 'IndividualSimulator',
success: function (result) {
$('#selectMRPC').empty();
JSON.parse(result).forEach(function (mrpc) {
var option = $('<option>', {
value: mrpc.name,
text: mrpc.name
});
//Persist data with option
option.data('mrpc', mrpc);
$('#selectMRPC').append(option);
});
},
error: function () {
}
});
return false;
}
});
triggerchange after binding the change event not before.option:selecteddoesn't exist yet.$('#selectMRPC')must exists first.