asp.net mvc 4 - JQuery/MVC selected option does nog change from script -
in mvc application have 2 drop-down lists. second gets populated based on choice made in first one. 'start' value db pushed view second drop-down setting data-zatara-workyearid attribute. updating second 1 done updateworkyeardropdown() function. after loading document call function populate second dropdown start on. far good.
the result :
<select class="form-control" data-val="true" data-val-number="the field work year must number." data-val-required="the work year field required." data-zatara-workyearid="6" id="workyearid" name="workyearid"> <option value="4">boekjaar 2014</option> <option value="5">boekjaar 2015</option> <option value="6">boekjaar 2016</option> </select>
in $(document).ready function try set selected value value stored in data-zatara-workyearid. here goes wrong. have tried dozen combination working, none of them work. pasting code in console job.
the full script : function updatewordkyeardropdown() { var $id = $('#tenantid option:selected').attr('value'); $('#workyearid').html(''); $.getjson('/activitiesadmin/_workyearsfortenant/' + $id, function (data) { $(data).each(function (index, item) { $('#workyearid').append($('<option>', { text: item.text, value: item.value })); }); }); $('#linkedstaffmemberfilter').attr('data-zatara-tenantid', $id); $('.linkedstaffmembercontainer').remove(); }; $(document).ready(function () { updatewordkyeardropdown(); var $workyearid = $('#workyearid').attr('data-zatara-workyearid'); if (typeof $workyearid !== typeof undefined && $workyearid !== false) { $selectorstring = '#workyearid option[value="'+$workyearid+'"]'; $($selectorstring).prop("selected", true); } else { console.log('atrr not found'); } }); $('#tenantid').change(function () { updatewordkyeardropdown(); });
thx suggestion of jasen moved $(document).ready function. hence took litle different approach setting selected value, intended to.
the final working code.
function updatewordkyeardropdown() { var $id = $('#tenantid option:selected').attr('value'); $('#workyearid').html(''); $('#linkedstaffmemberfilter').attr('data-zatara-tenantid', $id); $('.linkedstaffmembercontainer').remove(); var $workyearid = $('#workyearid').attr('data-zatara-workyearid'); if (typeof $workyearid == typeof undefined || $workyearid == false) { $workyearid = "0"; } $.getjson('/activitiesadmin/_workyearsfortenant/' + $id, function (data) { $(data).each(function (index, item) { if (item.value == $workyearid) $('#workyearid').append($('<option>', { text: item.text, value: item.value, selected: true })); else $('#workyearid').append($('<option>', { text: item.text, value: item.value, selected: false })); }); }); }; $(document).ready(function () { updatewordkyeardropdown();}); $('#tenantid').change(function () { updatewordkyeardropdown(); });
Comments
Post a Comment