#javascript #jquery #ajax #selected #selectedvalue
Вопрос:
Я использую https://geodata.solutions Я пытаюсь добавить атрибут «выбранный» в параметр страна Германия, у меня есть параметр «$ user [‘страна’]», в котором указано значение «Германия», если кто-то столкнулся с этой проблемой и знает, как ее решить. я не могу понять, где код javascript проверяет, куда поместить выбранный атрибут*$user[страна’]; // Германия*
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
}
var errorRes = function(e) {
console.log(e);
//alert("Error found nError Code: " e.status " nError Message: " e.statusText);
//jQuery('#loader').modal('hide');
}
jQuery.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
var rootUrl = "//geodata.solutions/api/api.php";
//set default values
var username = 'demo';
var ordering = 'name';
//now check for set values
var addParams = '';
if(jQuery("#gds_appid").length > 0) {
addParams = 'amp;appid=' jQuery("#gds_appid").val();
}
if(jQuery("#gds_hash").length > 0) {
addParams = 'amp;hash=' jQuery("#gds_hash").val();
}
var call = new ajaxCall();
this.confCity = function(id) {
// console.log(id);
// console.log('started');
var url = rootUrl '?type=confCityamp;countryId=' jQuery('#countryId option:selected').attr('countryid') 'amp;stateId=' jQuery('#stateId option:selected').attr('stateid') 'amp;cityId=' id;
var method = "post";
var data = {};
call.send(data, url, method, function(data) {
if(data){
// alert(data);
}
else{
// alert('No data');
}
});
};
this.getCities = function(id) {
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#cityId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = 'amp;addClasses=' encodeURIComponent(acC);
}
var url = rootUrl '?type=getCitiesamp;countryId=' jQuery('#countryId option:selected').attr('countryid') 'amp;stateId=' id addParams addClasses;
var method = "post";
var data = {};
jQuery('.cities').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.cities').find("option:eq(0)").html("Select City");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded count:' data.hits ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' data.hits ' of 1000')
}
var listlen = Object.keys(data['result']).length;
if(listlen > 0)
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
jQuery('.cities').append(option);
});
}
else
{
var usestate = jQuery('#stateId option:selected').val();
var option = jQuery('<option />');
option.attr('value', usestate).text(usestate);
option.attr('selected', 'selected');
jQuery('.cities').append(option);
}
jQuery(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getStates = function(id) {
jQuery(".states option:gt(0)").remove();
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#stateId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = 'amp;addClasses=' encodeURIComponent(acC);
}
var url = rootUrl '?type=getStatesamp;countryId=' id addParams addClasses;
var method = "post";
var data = {};
jQuery('.states').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.states').find("option:eq(0)").html("Select State");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' data.hits ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' data.hits ' of 1000')
}
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('stateid', key);
jQuery('.states').append(option);
});
jQuery(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
//get additional fields
var countryClasses = jQuery('#countryId').attr('class');
var cC = countryClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = 'amp;addClasses=' encodeURIComponent(acC);
}
var presel = false;
var iip = 'N';
jQuery.each(cC, function( index, value ) {
if (value.match("^presel-")) {
presel = value.substring(7);
}
if(value.match("^presel-byi"))
{
var iip = 'Y';
}
});
var url = rootUrl '?type=getCountries' addParams addClasses;
var method = "post";
var data = {};
jQuery('.countries').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.countries').find("option:eq(0)").html("Select Country");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' data.hits ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' data.hits ' of 1000')
}
if(presel == 'byip')
{
presel = data['presel'];
console.log('2 presel is set as ' presel);
}
if(jQuery.inArray("group-continents",cC) > -1)
{
var $select = jQuery('.countries');
console.log(data['result']);
jQuery.each(data['result'], function(i, optgroups) {
var $optgroup = jQuery("<optgroup>", {label: i});
if(optgroups.length > 0)
{
$optgroup.appendTo($select);
}
jQuery.each(optgroups, function(groupName, options) {
var coption = jQuery('<option />');
coption.attr('value', options.name).text(options.name);
coption.attr('countryid', options.id);
if(presel) {
if (presel.toUpperCase() == options.id) {
coption.attr('selected', 'selected');
}
}
coption.appendTo($optgroup);
});
});
}
else
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('countryid', key);
if(presel)
{
if(presel.toUpperCase() == key)
{
option.attr('selected', 'selected');
}
}
jQuery('.countries').append(option);
});
}
if(presel)
{
jQuery('.countries').trigger('change');
}
jQuery(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
jQuery(function() {
var loc = new locationInfo();
loc.getCountries();
jQuery(".countries").on("change", function(ev) {
var countryId = jQuery("option:selected", this).attr('countryid');
if(countryId != ''){
loc.getStates(countryId);
}
else{
jQuery(".states option:gt(0)").remove();
}
});
jQuery(".states").on("change", function(ev) {
var stateId = jQuery("option:selected", this).attr('stateid');
if(stateId != ''){
loc.getCities(stateId);
}
else{
jQuery(".cities option:gt(0)").remove();
}
});
jQuery(".cities").on("change", function(ev) {
var cityId = jQuery("option:selected", this).val();
if(cityId != ''){
loc.confCity(cityId);
}
});
});
<select name="country" class="countries" id="countryId">
<option value="">Select Country</option>
</select>
<select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
<select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
после запуска javascript:
<select name="country" class="countries form-control" id="countryId">
<option value="">Select Country</option>
<option value="Afghanistan" countryid="AF">Afghanistan</option>
<option value="Albania" countryid="AL">Albania</option>
<option value="Algeria" countryid="DZ">Algeria</option>
<option value="Germany" countryid="DE">Germany</option> <!-- add attr selected-->
</select>
Комментарии:
1. Вы могли бы попробовать что-то вроде
$('#countryId [countryid="DE"]').prop("selected",true)
2. я пробовал это, но это не работает jsfiddle.net/95e3d14b
3. он нигде не видит мой код? Это сработало нормально, когда я его добавил jsfiddle.net/gnfv7uc1
4. фактически добавляет выбранное, но скрипт не понимает, что было выбрано значение для отображения следующего выбранного имени=»состояние».
5. вот так? jsfiddle.net/gnfv7uc1/1