JSON Results To A Drop down List - javascript

Hi I am Working On a Web Form..
I Have A combo Box for holding all The Units.
I Have Taken All The units from the Database Using JSON,now i need to Bind All these Units To the drop down List
How can I Do this...?
function getUnitFamily(pack_detl_ID,select) {
//***********************************//
PageMethods.getUnitFamily(pack_detl_ID,
function(result) {
if (result != null) {
custinfo = eval(result);
if (custinfo != null) {
$('#<%=drpUnit.ClientID%> option').remove();
var objSub = document.getElementById('<%=drpUnit.ClientID%>');
$.each(custinfo, function(i, item) {
listOpt = document.createElement("option");
listOpt.value = item[0];
listOpt.text = item[1];
objSub.add(listOpt);
});
alert(select);
document.getElementById('<%= drpUnit.ClientID %>').value = select;
}
}
}, pageMethodError);
With An example can any one explain

A combobox sounds like you are using an ASP.NET control. Of course, you can bind your items to that control in the code behind. If you are doing some AJAX stuff and have a dropdown ( element>) in your page which you want to populate at client side, you might want to take a look at what jQuery has to offer. For example use the AJAX api to retrieve your data and push that data into your dropdown like so:
var options = $("#options");
$.each(result, function() {
options.append($("<option />").val("sometext").text("sometext"));
});

In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Related

jQuery blur based checking and print result to a view in codeigniter

Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});

How to load json response which contain string values only to a combo box already created

I have a String array containing some names. I return it as a Json response and now I need to load those names in to a combo box in my html page. Combo box have been already created ans say its id is names. This is the function I wrote.
function loadSiteOfficers(ele){
var selected = ele.value;
if(selected == "Site Officer"){
jQuery.ajax({
type : "POST",
url : "/TFProject/load_officers.htm",
success : function(response) {
if (response.status == "SUCCESS") {
alert(response.result);
// load response results to the combo box
} else {
////// some code here
}
},
error : function(e) {
alert('Error: ' + e);
}
});
}
}
alert(response.result) gives me names separated by commas. They are retrieved from the database.
I am bit confused here and need to know how to load the data. I will be grateful if you can help me
Thanks.
try something like this...
$.each(response.result, function(key, value) {
$('#names').append($('<option></option>').val(key).html(value));
});

clearing dynamically created combo box options using javascript

I have a combo box with one option hard coded.
I will add the remaining options dynamically
Combo box with hard coded option:
<select id="connectionname" class="connectionname" onchange="display();"><option>---Select---</option></select>
Javascript function to create combo box options dynamically:
function showDbDlg(){
var newar=new Array();
try{
var xhrArgs = {
url: "./ReadDBDetails",
content: {MODE:"DBNAMES"},
handleAs: "text",
load: function(response) {
var dbNames = response.trim();
dbNames=dbNames.substring(0,dbNames.length-1);
dbArray=dbNames.split(",");
/*var selectValue = document.getElementById("connectionname").value;
alert(selectValue);*/
document.getElementById("connectionname").options.length = 0;
for(var i=0;i<dbArray.length;i++){
var newValue = document.getElementById("connectionname").appendChild(document.createElement('option'));
newValue.text = dbArray[i];
}
formDialog.show();
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
var deferred = dojo.xhrPost(xhrArgs);
}catch(e){alert(e);}
}
Before creating options dynamically, every time am using the below line to clear the existing options.
document.getElementById("connectionname").options.length = 0;
Its clearing the hard coded option as well.
My need is, i want to clear the dynamically created options alone.. not the hard coded one.
Have you tried this?
document.getElementById("connectionname").options.length = 1;

jQuery document ready call sequence

I have a following problem with jQuery. I use this code:
function populate_select_from_json(select, json_url) {
select.empty();
$.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo(select);
});
});
select.children(":first").attr("selected", true);
}
$(document).ready(function() {
var value_type = $("#value_type");
populate_select_from_json(value_type, SOME_URL);
var unit = $("#unit");
populate_select_from_json(unit, ANOTHER_URL + value_type.val());
});
I wanted to:
Load the document
Get some JSON data from an associated database
Put the data in #value_type <select> item
Get the value of #value_type select, and query the database once again to populate another select item.
The problem is, when I call value_type.val(), it always outputs null, even though the #value_type <select> is correctly populated. What am I doing wrong here?
I suppose something like this may work better with promises.
Along these lines (untested):
var populate_select_from_json = function($select, json_url) {
$select.empty();
return $.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo($select);
});
$select.children(":first").attr("selected", true);
});
};
$(document).ready(function() {
var $value_type = $("#value_type");
var $unit = $("#unit");
populate_select_from_json($value_type, SOME_URL).done(function(){
populate_select_from_json($unit, ANOTHER_URL + $value_type.val());
});
});

Jquery html() method doesn't work

Here is my code:
$(function () {
var region = $('#region');
var city = $('#city');
var pickedRegionId = region.find(':selected').val();
var options;
if (pickedRegionId === '') {
console.log('region is empty, html() and disable');
city.html('');
city.attr('disabled', true);
}
region.change(function(){
console.log('region is changed');
pickedRegionId = $(this).val();
if (pickedRegionId !== '') {
city.html('');
console.log('loading cities');
getCities(pickedRegionId);
}
});
function getCities (regionId) {
city.attr('disabled', true);
city.html('<option>Loading...</option>');
$.get(
'/ajax/get_cities',
'region_id='+regionId,
function (responce) {
if (responce.result === 'success') {
$(responce.cities).each(function(){
options += '<option value="'+$(this).attr('id')+'">'+$(this).attr('city')+'</option>';
});
city.html(options);
city.attr('disabled', false);
}
}, 'json'
);
}
});
When page loads all is ok, I pick some region and select with cities fills with ajax data.
But when I pick another region, data in cities select just extends with newer data.
So the problem that I have cities from both regions(new and old one). And not matter how many times I pick another region it's just adding new data to city select. In the code all looks fine and on region change I've put .html('') so it should be empty before inserting received values. But I can't figure out what the bug is.
$(responce.cities).each(function(){
options += '<option value="'+$(this).attr('id')+'">'+$(this).attr('city')+'</option>';
});
You are just appending to options and not clearing it at all. I would empty your options just below where you set cities to loading.
try reseting your "options" var before the loop:
...
options = '';
$(responce.cities).each(function(){
...
You have to empty the variable options first. You're just adding new cities to the options variable.
The simplest solution would be to move the options variable into the getCities function like this:
function getCities (regionId) {
var options = "";
city.attr('disabled', true);
city.html('<option>Loading...</option>');
$.get(
'/ajax/get_cities',
'region_id='+regionId,
function (responce) {
if (responce.result === 'success') {
$(responce.cities).each(function(){
options += '<option value="'+$(this).attr('id')+'">'+$(this).attr('city')+'</option>';
});
city.html(options);
city.attr('disabled', false);
}
}, 'json'
);
}
The problem is that, when you receive the data, you add it to the options variable that is global. So, just add this before $(responce.cities).each(function(){:
options = '';
And everything should be fine.
BTW, it's response, not responce. :)
In function getCities, add var options=''; as the first line. You're constantly adding to it but never clearing it out, hence the problem.
Two things:
1) city.attr('disabled', true); should be city.prop('disabled', 'disabled');
2) Try resetting options back to an empty string before repopulating it like so:
if (responce.result === 'success') {
options = '';
$(responce.cities).each(function(){
options += '<option value="'+$(this).attr('id')+'">'+$(this).attr('city')+'</option>';
});
city.html(options);
city.attr('disabled', false);
}

Categories

Resources