jQuery add selected to option after post data

Viewed 62

I add json data into option data-values In action when I click on option, my jQuery code add data-values data to option list in #target using JSON.parse, each, and append methods.

$('#list').change(function() {
  var response = JSON.parse($(this).find(':selected').attr('data-values'));
  var len = response.length;
  $("#target").empty();
  $.each(response, function() {
    $.each(this, function(name, value) {
      $("#target").append("<option value='" + name + "'>" + value + "</option>");
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="list">
  <optgroup label="Hardware">
    <option value="5" data-values='[{"34":"500GB","35":"1TB","36":"2TB","37":"4TB"}]'>
      HDD
    </option>
    <option value="11" data-values='[{"63":"Ardreno 650","64":"Adreno 640","65":"NVIDIA GeForce GTX 1650","66":"NVIDIA GeForce GTX 1080","67":"NVIDIA GeForce GTX 2070","68":"NVIDIA GeForce GTX 2080"}]' selected="selected">
      Graphics
    </option>
  </optgroup>
</select>

<select id="target"></select>

Now, in create page my code work true, But I have a big problem in post back. When I send data to my php controller and my controller return any error, I need to add old select data (send data) into #target list. Actually I need to auto load #target list on page load if #list option is selected and add selected to #target option list.

Worked demo

Doesn't work demo (add selected to option)

1 Answers

Try this: $('#list').trigger('change');

Related