Set selected multi selector option selected with json

I spent almost two days looking for a solution to my problem but found out nothing. Maybe I recently started learning Ajax and jquery stuff, I missed something.

Note. My all selected checkboxes are "Multiple Select Box Selected" and all options are hardcoded.

I have multiple text and select fields in which I want to display / select data from mysqli json database. One of the select event select event (basically, using this user can copy / edit existing data stored in db for all text and select boxes).

I have successfully accomplished this for text fields using the following js code that I have learned over the past two days to get my task done.

$(document).ready(function () 
{
   $('#posted_jobs').on('change', function () 
   {
      var selectedValue = $(this).val();    
      $.ajax
      ({
          url: 'Copyvalue.php',
          type: 'POST',
          data: 'filter_job_id=' + selectedValue,
          success: function(response) 
          {
            var obj = $.parseJSON(response);//parse JSON            
            console.log(response);
            //alert(JSON.stringify(obj));       
            $("#Job_Type").val(["Normal"]); // have tried manually adding value to selectbox here but not working
            $('#Locations').val(obj[0].Job_type); // have tried manually adding value to selectbox here but not working
            $('#Job_Type').val(obj[0].Job_type);
            $('#Keywords').val(obj[0].Keywords);
            $('#designation').val(obj[0].Designation);
            $('#Company_name').val(obj[0].Company_Name);
            $('#Contact_Person').val(obj[0].Contact_person_name);
            $('#Contact_person_no').val(obj[0].Contact_No);
            $('#Job_name').val(obj[0].Job_name);
           }
        });         
     });
  });

      

I tried n number of options from stack-overflow and other web suggestions. but not able to get this to work for pick boxes. Please help me get this working and if possible tell me a good source from where I can find out.

tried options like

$("#Locations").val(["1, 2, 3, 4"]).prop("selected", false);
$("#Locations").val([1, 2]);

      

My PHP script Json output in Chrome console

 [{"Job_id":"6","Employer_id":"2","creation_on":"2015-01-03 18:48:58","Keywords":"operation executive, manager operation, operation manager, executive operation","Job_type":"Normal","Designation":"Assistant Manager - Operation","Open_Positions":"4","Job_Description":"<p><strong>Good<\/strong> <em>Position<\/em><\/p>","Min_age":"23","Max_age":"34","Min_exp":"5","Max_exp":"12","Min_salary":"104","Max_salary":"109","Hide_Salary":"","Locations":"3, 4, 8, 45, 46","Industry":"10002, 10004","FA":"1002, 1003","Education":"4, 6, 9","Company_Name":"Aviva Life Insurance Company India Limited","About_Company":"<p><strong>Good<\/strong><em> Company<\/em><\/p>","Contact_person_name":"Balvinder Rayat","Contact_No":"9818906677","Refresh_type":"15","Response_type":"VC","Job_name":"Operation AM","Job_status":"Active"}]

      

My block of choice

<select id="Locations" name='Locations[]' style='width:100%;' data-placeholder='Type or select   
locations' multiple class='chosen-select-no-results'>
    <option value="1">Bangalore</option>
    <option value="2">Chennai</option>
    <option value="3">Delhi</option>
    <option value="4">Gurgaon</option>
    <option value="5">Hyderabad</option>
    <option value="6">Kolkata</option>
    <option value="7">Mumbai / Navi Mumbai</option>
</select>                      

      

+3


source to share


4 answers


I searched a little more and got a solution (I think) to set the value of a select box specifically to (Selected selection)

basically the trigger was not from the code that was causing all the problems. After adding a trigger to the last values ​​retrieved with json, this was all solved.

$("#Job_Type").val(obj[0].Job_type).trigger('chosen:updated');

      

Hope it helps others too!



found the answer at this link Link

Also, for a multiple select box, if you have values ​​like [1,2,3,4], you can achieve the result using the following:

var values = obj[0].Locations;
$.each(values.split(','), function(index, element)
{
   $('#Locations').find('option[value="'+ element +'"]').attr('Selected', 'Selected');
   $("#Locations").trigger('chosen:updated');   
});

      

+4


source


I too had a similar issue when populating <select>

using the selected jQuery plugin and for setting some default options. The approach I used in my code was similar:

  • Get JSON response from ajax call
  • Populate the element <select>

    with JSON
  • Iterating through elements <option>

  • Update them with the "selected" attribute (for certain options)

Below are the code snippets that I used.



var response = "[{\"id\":\"1\",\"location\":\"Chennai\"},{\"id\":\"2\",\"location\":\"Bangalore\"},{\"id\":\"3\",\"location\":\"Hyderabad\"},  {\"id\":\"4\",\"location\":\"Goa\"},{\"id\":\"5\",\"location\":\"Delhi\"},{\"id\":\"6\",\"location\":\"Mumbai\"},{\"id\": \"7\",\"location\":\"Cochin\"},{\"id\":\"8\",\"location\":\"Trivandrum\"}]";

/*populate <select> with the list of locations*/
var locationList = JSON.parse(response);
$.each(locationList, function() {
  $("#location-select").append($("<option/>")
    .val(this.id).text(this.location));
});
$("#location-select").chosen({
  no_results_text: "Oops, no location found!",
  display_selected_options: false
});

/*Make some locations from the list to be selected by default*/
var selectedLoc = JSON.parse("[{\"id\":\"2\",\"location\":\"Bangalore\"},{\"id\":\"6\",\"location\":\"Mumbai\"},{\"id\": \"7\",\"location\":\"Cochin\"}]");

/*
 *Create an array of locations, it can be array of id also,then
 * the if condition should be
 * if ($.inArray($(this).val(), users) != -1){...}
 * This is because id is populated as
 * <select>
 *  <option value="id from json"> location from json </option>
 * </select>
 */
var locations = [];
$.each(selectedLoc, function() {
  locations.push(this.location);
});

$("#location-select option").each(function() {
  if ($.inArray($(this).text(), locations) != -1) {
    $(this).attr('selected', 'selected');
    $("#location-select").trigger('chosen:updated');
    return;
  }
});
      

<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.min.js"></script>
<h3>
jQuery Chosen multiselect with selected values by default
</h3>
<select id="location-select" data-placeholder="Select locations..." style="width:95%;" multiple class="chosen-select"></select>
      

Run codeHide result


+4


source


I wrote a simple example http://jsfiddle.net/f7z664u5/

instead of this part

if($(this).val() == 1)
{
    $(this).prop('selected', true);
}
if($(this).val() == 2)
{
    $(this).prop('selected', true);
}

      

check if the value in the array is .. or what type you store the data in.

0


source


This will work.

$.each(objlist, function (index, value) {                                  
  $(".chosen-select option[value=" + value.id+ "]").attr("selected", "selected");
  $(".chosen-select").trigger("chosen:updated");                             
});

      

0


source







All Articles