Dom problem in AJAX request
I have been stuck with this issue for almost 2 days, consider the following code:
'. country-select 'occurs twice in the form (input),
$('.branch-row').hide();
$('.country-select').change(function(){
console.log($(this));
country_select = $(this);
$.get('get_country_branches.php',
'country=' + $("'#" + country_select.attr('id') + " option:selected'").val() + '&field=' + $(':input:eq('+($(":input").index(country_select) + 1) +')').attr('name'),
function(html){
$(':input:eq('+($(":input").index(country_select) + 1) +')').html(html);
//debug 1
console.log(country_select);
country_select.parent().parent().next().show();
},
'html'
);
}).change();
//debug 2
console.log(country_select);
the output from debug 1 is the same object:
[select # pays-dem.country-select] [select # pays-dem.country-select]
however the output from debug 2 is correct:
[select # Pays-enlev.country-select] [Select # pays-dem.country-select]
The problem seems to be with the $ .get () AJAX function and the country_select object. Any wtf idea continues?
a source to share
By not putting var in front of the country_select variable, it is bound to the global space, not the local function. Also, I don't think you need to query to get the selected value of the select. Use val()
should be enough. I would try to simplify the selection of what I think is the next entry after selection. Try something like this:
$('.country-select').change(function(){
console.log($(this));
var country_select = $(this);
$.get('get_country_branches.php',
'country=' + country_select.val() + '&field=' + country_select.next('input:first').attr('name'),
function(html){
country_select.next('input:first').html(html);
//debug 1
console.log(country_select);
country_select.parent().parent().next().show();
},
'html'
);
}).change();
By the way, this will break the console.log after the function, since the variable is no longer in the global scope.
a source to share
Just wanted to add some details to my answer above.
Whenever you use a variable in JavaScript without declaring it in the function scope (using the var keyword), it is added to the global window scope.
So the following will be true
function myFunction(){
i=99;
if(i==99 && window.i == i){
alert("It went into global scope");
}
}
myFunction();
if(i==99 && window.i == i){
alert("Same here");
}
a source to share