I have a text box
that is used to search for data
in a database
(Order Number). The data
returned (Products) is then added into a select
as an option
. The data
is then removed from select
when the user changes the data
in the text box
.
The functionality of this is somewhat working as I wanted, however I am having the options
duplicated and not all of the options
are removed.
I am unsure to where I am going wrong within the code, and would appreciate some guidance.
$(document).ready(function() {
$('#order_number').on('keyup', function(e) {
var myCustomer = document.getElementById('customer');
myCustomer.value = "";
var mySelect = document.getElementById('product');
var products_from_query = '';
var code = (e.keyCode || e.which);
// do nothing if it's an arrow key
if (code == 37 || code == 38 || code == 39 || code == 40) {
return;
}
var keyword = $('#order_number').val();
if (keyword.length) {
$.ajax( {
url: '../stocks/order_search',
type: 'GET',
dataType: 'json',
data: "keyword=" + keyword,
success: function(data) {
var length = mySelect.options.length;
for (i = 0; i < length; i++) {
mySelect.options[i] = null;
}
for (var i = 0; i < data.length; i++) {
newOption = document.createElement('option');
newOption.value = data[i]['ProductName'];
var options_seperator = ' - ';
var options_product_name = data[i]['ProductName'];
var options_product_description = data[i]['ProductDescription'];
var options_data = options_product_name.concat(options_seperator).concat(options_product_description);
if (typeof newOption.textContent === 'undefined') {
newOption.innerText = options_data;
} else {
newOption.textContent = options_data;
}
mySelect.appendChild(newOption);
};
myCustomer.value = data[0]['Customer'];
}
})
}
});
});
You need to add following one line before ajax call.
mySelect.html('');