ujjawl saini
ujjawl saini

Reputation: 133

jQuery-set dynamic dropdown value

I have a dropdown

<select id="DropdownId" label="condition " ></select>

Below is the code, from where i am filling values into the dropdown:

var request = $.ajax({'url': '/getDropdownValues'}); 
request.done(function(response) 
{   
    response = JSON.parse(response)
    var processbyList=[]; 
    $.each(response, function(index, element) {
           processbyList.push(element.processby); 
    });
    $("#DropdownId").select2({
            data: processbyList
    });
    });
    request.fail(function(jqXHR, textStatus) 
    {
        alert('Request failed: ' + textStatus);
    });

I want to set a value inside dropdown. How can I set the dropdown value using jQuery?

Here 'responseitem' is the value which i am getting from some ajax call and i want this value to set into the dropdown.

I have tried using

1. `document.getElementById("DropdownId").value = responseitem;`

2.  `$('#DropdownId').val(responseitem);`

But nothing worked for me. Am I missing something or where I am wrong? How to achieve this?

EDIT:

On button click event i am creating a table inside that this dropdown is in one in one column of it.

function onButtonClick(){

// to fill values in dropdown
var request = $.ajax({'url': '/getDropdownValues'}); 
request.done(function(response) 
{   
    response = JSON.parse(response)
    var processbyList=[]; 
    $.each(response, function(index, element) {
       processbyList.push(element.processby); 
    });
    $("#DropdownId").select2({
        data: processbyList
    });
});
request.fail(function(jqXHR, textStatus) 
{
    alert('Request failed: ' + textStatus);
});

//this is again inside an ajax call
var requestRegex =$.ajax({url:'/Info',
                         data:"FieldName="+responseitem[0],
                         processData: true,
                         contentType: "application/json",
                         dataType:    "json",
                         });
requestRegex.done(function(responseRegex) 
{
    var panel=document.createElement("panel");  
    var h = '<div class="panel panel-default" >';
    h += '<div class="panel-heading fixed-panel">';
    h +='<h3 class="panel-title">'+responseitem[0]+'</h3>';
    h +='<span class="pull-right clickable"></span>';
    h += '</div>'; 
    h +='<div class="panel-body">';
    h += '<div class="table-responsive">';
    h +='<table id="' +"albums"+ '" cellspacing="0"  class="table-bordered table-hover specialCollapse>';
    h +='<thead></thead>';
    h +='<tbody id="' +"tbody"+ '">';

    h +='<tr>';
    h +='<td><h4><bold>Process By</bold></h4></td>';
    //h +='<td id="' +"processBy"+ '"><textarea class="form-control" rows="1" style="max-width: 30%;">'+ responseitem[2] + '</textarea></td>';
    h +='<td id="' +"processBy"+ '"><select id="DropdownId"  style="width:200px;" value="' +responseitem[2]+ '" ></select></td>';
    h +='</tr>';

    h +='</tbody>';
    h +='</table>';
    h += '</div></div>';

    panel.innerHTML = h;
    $("#DropdownId").select2();
    $("#DropdownId").val(responseitem[2]).trigger("change");

  });   
  request.fail(function(jqXHR, textStatus) 
  {
    alert('Request is failing: ' + textStatus);
  });
}   

EDIT:

 document.getElementById("DropdownId").value=responseitem[2];

This is showing correct output in console:

document.getElementById("processbyDropdownId").value=responseitem[2];
 >>>"page"

But not in the jQuery UI.I dont want to refresh my entire page. I just want to refresh such that only the dropdown value refreshes.

Upvotes: 1

Views: 6462

Answers (1)

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

As you using select2 plugin, you need to trigger change event after set the new value

$('#DropdownId').val(responseitem).trigger('change');

Obviously, responseitem must be one of #DropdownId's items.

You can read more about that here

Update

As you didn't provide enough info in your question, using jsonplaceholder.typicode.com, I created demo to show you how you can change select value after an ajax request (I used select2 too):

HTML

<select style="width: 200px;">
  <option value="1">Leanne Graham</option>
  <option value="2" selected="selected">Ervin Howell</option>
  <option value="3">Clementine Bauch</option>
</select>

JS

$("select").select2();

setTimeout(function() {
  $.ajax("https://jsonplaceholder.typicode.com/users", {
    type: "GET",
    success: function(res) {
      var id = -1;
      for (var i in res) {
        if (res[i].name == "Clementine Bauch") {
          id = res[i].id;
          break;
        }
      }

      $("select").val(id).trigger("change");
    }
  });
}, 1000);

Codepen

You will see after 1 second the selected value of select will be changed to Clementine Bauch.

Seems like you updated your question, so, you missing option inside select, change your code as follow:

h += '<td id="' + "processBy" + '"><select id="DropdownId"  style="width:200px;"><option value="' + responseitem[2] + '">"' + responseitem[2] + '"</option></select></td>';

Upvotes: 2

Related Questions