1

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.

ujjawl saini
  • 133
  • 3
  • 15

1 Answers1

2

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>';
Community
  • 1
  • 1
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
  • I have tried every answer given in the link provided by you, but none of them worked in my case. `$('#DropdownId').val(responseitem).trigger('change');` `$('#DropdownId').selectmenu().selectmenu('refresh', true);` `$('#DropdownId').val(responseitem).change(); ` `$('#DropdownId').val(responseitem).trigger('change.select2');` `$("#DropdownId").select2("data", { id: 1, text: responseitem });` `$("#DropdownId").select2().select2("val", responseitem);` `$("#DropdownId").select2(); $("#DropdownId").val(responseitem).trigger("change");` These all i have tried :( – ujjawl saini May 05 '17 at 11:37
  • @ujjawlsaini please add `console.log(response)` to `.done` function and put the result in your question, I'm sure about my mentioned solution, I used `select2` before. – Mehdi Dehghani May 05 '17 at 12:55
  • @ujjawlsaini I updated my answer, check the demo on Codepen. – Mehdi Dehghani May 05 '17 at 13:20
  • @ Mehdi Dehghani i tried exactly same solution provided by you, but didn't worked for me. I've edited my question, can you look once, i guess i am missing something . – ujjawl saini May 09 '17 at 04:41
  • @ujjawlsaini Can you provide Codepen or JSFiddle link, so I can test your code? you can use [jsonplaceholder.typicode.com](http://jsonplaceholder.typicode.com/) for test data. btw, what is `responseitem`? – Mehdi Dehghani May 09 '17 at 07:17
  • ..`` This is exactly what i was trying to do. Thanks a lot dude! – ujjawl saini May 09 '17 at 07:41
  • 1
    Glad to help mate, just a quick note, if you can avoid adding `HTML` like that way, use `semantic templating system`, such as http://handlebarsjs.com instead. its powerful and simple to edit and maintenance. happy coding ;) – Mehdi Dehghani May 09 '17 at 09:03
  • @ Mehdi Dehghani sure, will check that out! :) – ujjawl saini May 09 '17 at 10:35