How to assign option value for select after ajaxcall - javascript

I have this html:
<select id="test"></select>
And This ajax code:
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//url: localhost/web/index.php?name='whatever'
var value = get('name');
$(document).ready(function(){
$('select').select2();
$.ajax({
type: "POST",
url: 'getValues.php',
data: {'test': $("#test").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#test"), options = '';
select.empty();
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
});
</script>
I need to set the value of select as taken from the url,which is (var value).
The value is working fine,as I tested it in alert.
Any help is appreciated

1) You can use .val() after appending options:
select.append(options);
select.val(value);
2)
or add attribute selected to option having same value while building the options html string.
options += "<option value='"+data[i].id+"' "+(data[i].id == value ? "selected" : "") +">"+ data[i].name +"</option>";

Chances are its the AJAX that is causing the issue. you need to trim() the response to remove a whitespace at the end of the returned data. Try the following :
success: function(data) {
var response = data.trim(), select = $("#test"), options = '';
select.empty();
for(var i=0;i<response.length; i++)
{
options += "<option value='"+response[i].id+"'>"+ response[i].name +"</option>";
}
select.append(options).val(value);
}

My problem is solved.
The problem was that the returned value has space,which is taken from url as +
So I replaced "+" by " "
Thanks all !

Related

Getting duplicate values in Drop down list in JavaScript AJAX Response

I'm trying to show multiple selected values in drop down list coming from database. My drop down list is dependent on another drop down list.
My JS code is:
var cityName = <?= json_encode($cityName); ?>;
var area_name = document.getElementById('area_name').value;
$.ajax({
'url': '<?= base_url('utility/cityByArea'); ?>',
'type': 'POST',
'dataType': 'JSON',
'data': {
area_name : area_name
},
success: function(response) {
$('#city_name').find('option').not(':first').remove();
$.each(response, function(index, data) {
for(var i = 0; i < cityName.length; i++) {
$('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(cityName[i] == data['city_id_primary'] ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
}
});
}
});
I'm getting correct selected values in drop down list, but the values in list is repeated.
I'm getting database value using php codeigniter code var cityName = <?= json_encode($cityName); ?>; in array form.
This is the console.log(cityName); output.
I'm getting output in drop down list.
Need to show single values.
Any kind of help is welcome, thanks in advance.
Right now your code is outputting every city cityName.length times, because you're doing the append() operation inside both of your loops.
If you want to set multiple options as selected based on what's in the cityname list, then all you need to do is split the bit where you check for a match in the cityName list away from the bit where you append the option to the dropdown.
The logic is quite simple:
success: function(response) {
$('#city_name').find('option').not(':first').remove();
//loop through each possible option
$.each(response, function(index, data) {
var selected = false; //boolean variable to store whether the option value matches any existing city, or not
//loop through the existing cities
for(var i = 0; i < cityName.length; i++) {
if (cityName[i] == data['city_id_primary']) {
selected = true; //we have a match
break; //no need to carry on checking, so stop the loop
}
}
//now append the option to the dropdown (once!) and set its selected attribute according to the value of the "selected" boolean.
$('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(selected === true ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
});
}
P.S. There's probably a "neater" way to write that using some jQuery array functions but that's the simplest version to understand.
Change logic of 2 each functons:
for (var i = 0; i < cityName.length; i++) {
$.each(response, function (index, data) {
$('#city_name').append('<option value="' + data['city_id_primary'] + '" ' + (cityName[i] == data['city_id_primary'] ? ' selected ' : '') + '>' + data['city_name'] + '</option>');
});
}

How to get JSON data into option list

I am getting JSON in the following format (as array of objects)
[{"0":"Ahmednagar","city_name":"Ahmednagar","1":"1","city_id":"1"},{"0":"Akola","city_name":"Akola","1":"2","city_id":"2"},{"0":"Amravati","city_name":"Amravati","1":"3","city_id":"3"},{"0":"Aurangabad","city_name":"Aurangabad","1":"4","city_id":"4"},{"0":"Beed","city_name":"Beed","1":"5","city_id":"5"},{"0":"Bhandara","city_name":"Bhandara","1":"6","city_id":"6"},{"0":"Buldhana","city_name":"Buldhana","1":"7","city_id":"7"},{"0":"Chandrapur","city_name":"Chandrapur","1":"8","city_id":"8"},{"0":"Dhule","city_name":"Dhule","1":"9","city_id":"9"},{"0":"Gadchiroli","city_name":"Gadchiroli","1":"10","city_id":"10"},{"0":"Gondia","city_name":"Gondia","1":"11","city_id":"11"},{"0":"Hingoli","city_name":"Hingoli","1":"12","city_id":"12"},{"0":"Jalgaon","city_name":"Jalgaon","1":"13","city_id":"13"},{"0":"Jalna","city_name":"Jalna","1":"14","city_id":"14"},{"0":"Kolhapur","city_name":"Kolhapur","1":"15","city_id":"15"},{"0":"Latur","city_name":"Latur","1":"16","city_id":"16"},{"0":"Mumbai City","city_name":"Mumbai City","1":"17","city_id":"17"},{"0":"Mumbai Suburban","city_name":"Mumbai Suburban","1":"18","city_id":"18"},{"0":"Nagpur","city_name":"Nagpur","1":"19","city_id":"19"},{"0":"Nanded","city_name":"Nanded","1":"20","city_id":"20"},{"0":"Nandurbar","city_name":"Nandurbar","1":"21","city_id":"21"},{"0":"Nashik","city_name":"Nashik","1":"22","city_id":"22"},{"0":"Osmanabad","city_name":"Osmanabad","1":"23","city_id":"23"},{"0":"Palghar","city_name":"Palghar","1":"36","city_id":"36"},{"0":"Parbhani","city_name":"Parbhani","1":"24","city_id":"24"},{"0":"Pune & Pimpri-Chinchwad ","city_name":"Pune & Pimpri-Chinchwad ","1":"25","city_id":"25"},{"0":"Raigad","city_name":"Raigad","1":"26","city_id":"26"},{"0":"Ratnagiri","city_name":"Ratnagiri","1":"27","city_id":"27"},{"0":"Sangli","city_name":"Sangli","1":"28","city_id":"28"},{"0":"Satara","city_name":"Satara","1":"29","city_id":"29"},{"0":"Sindhudurg","city_name":"Sindhudurg","1":"30","city_id":"30"},{"0":"Solapur","city_name":"Solapur","1":"31","city_id":"31"},{"0":"Thane","city_name":"Thane","1":"32","city_id":"32"},{"0":"Wardha","city_name":"Wardha","1":"33","city_id":"33"},{"0":"Washim","city_name":"Washim","1":"34","city_id":"34"},{"0":"Yavatmal\t","city_name":"Yavatmal\t","1":"35","city_id":"35"}]
ajax call to get json
$(document).ready(function(){
$("#select_state").change(function() {
var $state_var=$('#select_state').val();
alert("Selected State Value "+$state_var);
//make the ajax call
$.ajax({
url: 'ajax/location.php',
type:'GET',
data: {
state_name : $state_var
},
success: function(city_list) {
console.log(city_list);
var options = '';
for (var i = 0; i < city_list.length; i++) {
var city = city_list[i];
options += '<option value="' + city.city_id + '">' + city.city_name + '</option>';
}
$('#select_city').html(options);
$('#select_city').show();
}
});
});
});
Now it gives me only undefined is option list
You need to add:-
dataType;'json',
In your $.ajax code so that your response is automatically parsed and success function will execute properly.
Like below:-
$.ajax({
url: 'ajax/location.php',
type:'GET',
dataType:'json', // add this
data: {
state_name : $state_var
},.....rest code

how to clean option values under select - html tag

I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});

Ajax returning an undefine value

I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));

jQuery populate select issues with onclick

I've manage to create a sample in jsfiddle http://jsfiddle.net/9vkk5/ to illustrate my problem
As you might see it's only an example because I fill the select with information by database, this way:
$.ajax({
type: "POST",
url: "load.php?type=clients",
dataType: 'json',
success: function(data){
$("#clients").empty();
var options = '';
for(var i = 0; i <= data.length - 1; i++){
options += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#clients").append(options);
$("#clients").trigger('chosen:updated');
}
});
But the problem I have is totally the same as the jsfiddle example. I would like to, whenever I click the select to fill with data from database but keep the actual option selected.
Edit: Solved.
$("#clients").append(options);
$("#clients").val(selected_option); // trick is here
$("#clients").trigger('chosen:updated');
$("#clients").trigger('chosen:refresh');

Categories