What Is Causing This Javascript Code To Function The Way It Is?
I know stackoverflow tends to shy away from 'wall of text' posts, but I've been at this for about 4 hours and I can't figure it out, so I wanted to give as much information as poss
Solution 1:
It's because you have two functions that are in the global scope called "set_item"
Solution 2:
You are defining your functions in the global scope, and the second is overwriting the first. You could solve this by namespacing (for lack of a better term) your functions by sticking them into an object.
For example,
script.js
var country = {
autocomplete: function() {
var min_length = 0; // min caracters to display the autocompletevar keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'capoInstantSearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
},
// set_item : this function will be executed when we select an itemset_item: function(item) {
// change input value
$('#country_id').val(item);
// hide proposition list
$('#country_list_id').hide();
$("#capoInfo").load("capoSingleReturn.php?q="+encodeURIComponent(item));
}
}
script2.js
var comp = {
compCheck: function() {
var min_length = 0; // min caracters to display the autocompletevar bootyTime = $('#comp_id').val();
if (bootyTime.length >= min_length) {
$.ajax({
url: 'capoInstantCompSearch.php',
type: 'POST',
data: {bootyTime:bootyTime},
success:function(data){
$('#comp_list_id').show();
$('#comp_list_id').html(data);
}
});
} else {
$('#comp_list_id').hide();
}
},
// set_item : this function will be executed when we select an itemset_item: function(item) {
// change input value
$('#comp_id').val(item);
// hide proposition list
$('#comp_list_id').hide();
$("#compReturn").load("capoCompReturn.php?w="+encodeURIComponent(item));
}
}
and then change the references in your HTML to include the namespace, e.g.
input box 1 (note the onkeyup
)
<input id="country_id"type="text" placeholder="Enter a Part Number"
onsubmit="this.value=this.value.toUpperCase()" autocomplete="off" onkeyup="country.autocomplete()">
<ul id="country_list_id"></ul>
and then repeat for all the other references, including the one in the PHP code.
You may also want to check out Browserify which brings Node's require
module syntax to the browser. Additionally, you might read up on closures and IIFE's in JS.
Post a Comment for "What Is Causing This Javascript Code To Function The Way It Is?"