Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set chosen multiselect option value as selected using json

I have spent almost two days searching for solution of my problem but didn't find out any. May be i have recently started learning Ajax & jquery stuff, i missed something.

Note: My all select boxes are Chosen Multiple select box & all options are hard coded.

I have multiple text & select boxes in which i want to display/select data from mysqli json output basis one of one select box change event (Basically using this user can copy/edit existing details saved in db for all text & select boxes).

I have been successfully able to execute this for text boxes using following js code which i learnt in last two days to accomplish my task

$(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 have tried n number of options from stack-overflow & other web suggestions. but not able to get this working for Select boxes. Kindly help me to get this working & if possible pls tell me good source from where i can learn this.

have 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 select box

<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>                      
like image 978
techworld Avatar asked Jan 10 '23 03:01

techworld


2 Answers

I too had similar issue while populating <select> using jQuery chosen plugin and to set some options as selected by default. The approach I used in my code was like,

  • Get JSON response from ajax call
  • Populate the <select> element using JSON
  • Iterate through the <option> elements
  • Update them with "selected" attribute (For particular options)

The code snippets I used were as follows.

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>
like image 199
Robin Raju Avatar answered Jan 18 '23 22:01

Robin Raju


i searched little more & got the solution (i guess) for setting select box value specially for (Chosen select box)

basically, trigger was missing from code which was causing all issue. Post adding trigger in last of values retrieved using json, it all got solved.

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

Hope it helps other too!!

found answer from this link Link

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

var values = obj[0].Locations;
$.each(values.split(','), function(index, element)
{
   $('#Locations').find('option[value="'+ element +'"]').attr('Selected', 'Selected');
   $("#Locations").trigger('chosen:updated');   
});
like image 26
techworld Avatar answered Jan 19 '23 00:01

techworld