baig772 baig772 - 3 months ago 7
Ajax Question

How to add disabled select property on select based on the json I got from the ajax

I have a materialize select box like

<select id="create-event-session-name" name="session_name" class="validate">
<option value="" disabled selected>Select Session</option>
<option value="measurements">Measurements</option>
<option value="bath">Bath</option>
<option value="post_partum">Post Partum</option>
<option value="nicu">NICU</option>
<option value="mics">Mics.</option>
</select>


I have a data from ajax call in which I have session names. I want to add disabled selected attribute to the option if that value exists in the
JSON
that I have

$('#create-event-user').on('change', function() {
var userId = $('#create-event-user').val();
var sessionStr = '<option value="" disabled selected>Select User</option>';
$.ajax({
type: 'GET',
url: "/get-user-sessions/" + userId,
success: function(data) {
$.each(data, function(index, item) {
console.info(item.session_name);
var mapped = $("select#create-event-session-name option").map(function() {
return $(this).val();
}).get();
console.info(mapped);
//console.info($('#create-event-session-name option[value = "''"]'));
});
},
error: function(jqXHR, textStatus, errorThrown) {

}
});
});

Answer

Select the options having the same value and if such a option exists set its slelected and disabled attribute:

 $.ajax({
    type: 'GET',
    url: "/get-user-sessions/" + userId,
    success: function(data) {
      $.each(data, function(index, item) {
        var opt = $('#create-event-session-name option[value="'+item.session_name+'"]');
        if(opt.length) {opt.attr('selected',true).attr('disabled',true);}
      });
    },
    error: function(jqXHR, textStatus, errorThrown) {

    }
  });
Comments