I'm using Chosen.js plugin for drop-down search in which I have fetch data successfully also saved it to database but I unable to retrieve those saved drop-down data from database to it's respective field using Ajax search.
I tried initializing chosen in success function but no luck, not giving any output but when I alert the response its working.
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').on('keydown', function(e) {
if(e.which == 13){
var sid = $("#search").val();
$.ajax({
url: '{{ URL::to('search-data/')}}'+"/"+ sid,
type: "Get",
dataType: 'json',
success: function(response){
$("#mob").val(response.mobile);//Working
$("#car").chosen().val(response.car_name);//Not Working
$("#car").val(response.car_name);//Not Working
//alert(response.car_name);//Working but in alert only
}
});
}
});
});
</script>
HTML:
<div>
<label for="car">Car Name</label>
<select class="form-control select-box" name="car" id="car">
<option>Select Car</option>
</select>
</div >
I want to retrieve saved drop-down values to its respective field.
You need to append options
to your select box and then trigger updated so that the chosen select-box get the updated changes. Working example:
//Suppose you need to append below variable
var response_car_name="abcd";
//append the option and then use trigger event to update select box
$("#car").chosen().append("<option>"+response_car_name+"</option").trigger("chosen:updated");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">
<div>
<label for="car">Car Name</label>
<select name="brand" id="car"class="form-control select-box " name="car" >
<option>Select Car</option>
</select>
</div >