Jquery ui autocomplete with barcode scanner, text is deleted on focusout - javascript

I have two input fields that come one after another:
<input class="inputItemNum ui-autocomplete-input" id="tbAutoItemCode1" name="tbAutoItemCode1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
<input class="inputItemName ui-autocomplete-input" id="tbAutoItemName1" name="tbAutoItemName1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
The first represents an item code and the other represents an item name.
On both of them I am using jquery-ui autocomplete and in 2 situations:
1) on input
2) on focus out
I need the autocomplete on focusout because I am using an android device with bar-code scanner that inserts two Tab characters as input suffix, so when reading input into the item num it does the autocomplete and when leaving the input element (with one of the tab suffix) it checks if the item num is ok (again with autocomplete - because the user might entered manually an item code that does not exists- in that case I will clean the input fields.)
Also need to mention that my autocomplete list comes from an ajax request.
The problem I am facing is that when reading the item num with the bar-code scanner it also fills in the item name (as expected) but sometimes it deletes the item name the second it was filled.
I thought it was related to the async ajax request (when the response comes back the tab suffix was already inserted and the fields were cleaned) so I tries using the ajax async:false but still no luck there. I hope someone can help me put.
here is my javascript code that uses the autocomplete:
$(document).on('input', '.inputItemNum', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 100,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ "prefixText": text, "count": 40, 'mode': 'code' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemCode,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
//openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
event.preventDefault();
//event.stopPropogation();
//focusQtyColumn(index);
focusItemNameColumn(index);
$(".ui-autocomplete").hide();
//addRow();
return false;
}
});
} // if length > 0
}); //keyup
$(document).on('keydown', '.inputItemNum', function (event) {
var code = event.keyCode || event.which;
if (code == '9') {
//alert("Tab Pressed");
event.stopPropagation();
return;
}
});
$('.inputItemNum').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
if ($(this).val() == "") { return; };
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + $(this).val() + "','count': '1','mode':'exact_code'}", //search for exact code!
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
// $("#tbAutoItemCode" + indexer).val("");
clearRowData(index);
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
})
}); //focusout
$(document).on('input', '.inputItemName', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 0,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ 'prefixText': text, 'count': 40, 'mode': 'name' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemName,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#discount" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
if(index == $('#orderTable tr:last').index()){
addRow();
}
return false;
}
});
} // if length > 0
}); //keyup
$('.inputItemName').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
var text = $(this).val().trim();
if (text.length == 0) { return };
setTimeout(function(){
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + text + "','count': '1','mode':'name'}", //search for name!
dataType: "json",
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
$("#tbAutoItemName" + index).val("");
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
//focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
}) }, 500);
}); //focusout
// for bar-code scanner
$(".inputItemNum").live('click', function () {
$(this).select();
});
$(".inputItemName").live('click', function () {
$(this).select();
});

Related

How to disable form button until function has fully complete

So everything in script works perfectly. However there is an issue in this part of the code:
var min = 1;
while (min < 200) {
var max = min + 30;
scan(fruitID, min, max);
var min = max;
}
What I want from this loop:
Computes max value
Calls scan() function
Waits until the ajax in scan has successfully gotten the data, and displayed it up on the screen.
Computes min value
Repeats the loop
The mistake is in step 3. It doesn't wait for ajax to get the data back and process it. It just straight away repeats the loop. How do I make the loop wait until the scan() function has fully finished.
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {fruitName:fruitName},
success : function(data){
if (data.code == 200){
$("#submit").html("Running Scan");
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
var min = 1;
while (min < 200) {
var max = min + 30;
scan(fruitID, min, max);
var min = max;
}
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>"+data.msg+"</ul>");
$(".display-error").css("display","block");
}
}
});
});
});
function scan(vFruitId, min, max) {
$.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {vFruitId: vFruitId, min: min, max: max},
success : function(data){
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div>
`);
})
}
});
}
<form>
<label for="fname">Fruit (only correct input is: banana)</label><br>
<input type="text" id="fruit-name" name="fruit" value="banana"><br>
<button type="submit" id="submit" value="Submit">Submit</button>
</form>
<div id="results">
</div>
note: your original code does not re-enable the form button, so the question title is a bit misleading
The solution is to use the Promise-like object returned by $.ajax
The following code uses arrow notation like in the question, but does not use async/await so would work anywhere the code in the question works
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {
fruitName: fruitName
},
success: function (data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
function runscan(min) {
return scan(fruitID, min, min+30)
.then(() => {
min = min + 30;
if (min < 200) {
return runscan(min);
}
});
}
runscan(1)
.then(() => {
// all done here
});
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
});
});
});
function scan(vFruitId, min, max) {
return $.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {
vFruitId: vFruitId,
min: min,
max: max
},
success: function (data) {
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div>
`);
})
}
});
}
Alternatively, using async/await, the main success code can be written
success: function(data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
(async function() { // `success` can't be async, because jquery doesn't like that
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
var min = 1;
while (min < 200) {
await scan(fruitID, min, min + 30);
min = min + 30;
}
})();
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
Important note: you still MUST return $.ajax in function scan as per first code snippet

clearInterval not working | undefined

I have such jQuery code and have problem with clearing intervals.
var secs = 50, width = 100;
var counter = function() {
if(secs > 0) {
secs--;
width = width - 2;
$('#time').css('width', width + '%').attr('aria-valuenow', width);
$('.seconds').html(secs);
} else if(secs == 0){
$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
clearInterval(counter);
setInterval(winner, 3000);
}
};
var winner = function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "game_results"
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "you") {
$('.waiting').addClass('hidden');
$('.you').removeClass('hidden');
} else if (data == "opponent") {
$('.waiting').addClass('hidden');
$('.opponent').removeClass('hidden');
}
}
});
console.log(clearInterval(winner)); // heer
}
function answer(question_id, answer, question) {
var question_higher = question_id + 1;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "play",
answer: answer,
question: question
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "wrong") {
$.playSound('build/sounds/wrong');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-danger');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
} else if (data == "correct") {
$.playSound('build/sounds/correct');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-success');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
}
}
});
if(question_id == 5) {
clearInterval(counter);
setTimeout(function() {
//$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
}, 750);
setInterval(winner, 3000);
}
}
$(document).ready(function() {
$('*[data-question="1"]').removeClass('hidden');
setInterval(counter, 1000);
});
Im trying to get this work for almost 5 hours without results.
Both clearInterval(counter); and clearInterval(winner) are not working and flooding my server with requets.
Thanks in advance for any help.
Let's see how you're clearing the interval.
clearInterval(winner)
where, winner is the function. To clear the interval, the ID of the interval should be passed as parameter.
When setting the interval, catch the interval ID in a variable
winnerInterval = setInterval(winner, 3000);
and use this variable to clear interval.
clearInterval(winnerInterval);
Make sure the variable containing interval ID is in the scope when clearing the interval.
See clearInterval.

jQuery AJAX 200 Undefined error with multiple / same name attributes[]

So I am submitting some data which some have the same name="" values like name="product_name[]" etc... which is why i think my current ajax is failing but not sure and not sure how to resolve. Anyone have any ideas? i.e
customer_name:James
customer_address_1:21 Test Road
customer_town:Test town
customer_postcode required:cm16 4rr
customer_email:james#email.com
customer_address_2:other part
customer_county:something
customer_phone:48486486486
customer_name_ship:James
customer_name_2_ship:other part
customer_town_ship:Test town
customer_address_1:21 Test Road
customer_county_ship:something
customer_postcode_ship:cm16 4rr
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:2
invoice_product_price[]:200
invoice_product_discount[]:20%
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:4
invoice_product_price[]:149
invoice_product_discount[]:
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:1
invoice_product_price[]:120
invoice_product_discount[]:40
invoice_subtotal:996.00
invoice_discount:120.00
invoice_shipping:40.00
invoice_vat:199.20
invoice_total:996.00
JSFiddle: http://jsfiddle.net/90jqq4ym/
JS:
$(document).ready(function() {
// add product
$("#action_add_product").click(function(e) {
e.preventDefault();
actionAddProduct();
});
// create invoice
$("#action_create_invoice").click(function(e) {
e.preventDefault();
actionCreateInvoice();
});
// enable date pickers for due date and invoice date
var dateFormat = $(this).attr('data-vat-rate');
$('#invoice_date, #invoice_due_date').datetimepicker({
showClose: false,
format: dateFormat
});
// copy customer details to shipping
$('input.copy-input').on("change keyup paste", function () {
$('input#' + this.id + "_ship").val($(this).val());
});
// remove product row
$('#invoice_table').on('click', ".delete-row", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
calculateTotal();
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table, #invoice_totals').on('change keyup paste', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
isPercent = $('[name="invoice_product_discount[]"]', tr).val().indexOf('%') > -1,
percent = $.trim($('[name="invoice_product_discount[]"]', tr).val().replace('%', '')),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0) {
if(isPercent){
subtotal = subtotal - ((parseFloat(percent) / 100) * subtotal);
} else {
subtotal = subtotal - parseFloat(percent);
}
} else {
$('[name="invoice_product_discount[]"]', tr).val('');
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal(){
var grandTotal = 0,
disc = 0;
$('#invoice_table tbody tr').each(function() {
var c_sbt = $('.calculate-sub', this).val(),
quantity = $('[name="invoice_product_qty[]"]', this).val(),
price = $('[name="invoice_product_price[]"]', this).val() || 0,
subtotal = parseInt(quantity) * parseFloat(price);
grandTotal += parseFloat(c_sbt);
disc += subtotal - parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal),
vat = parseInt($('.invoice-vat').attr('data-vat-rate')),
c_ship = parseInt($('.calculate.shipping').val()) || 0,
withShip = parseInt(subT + c_ship);
$('.invoice-sub-total').text(subT.toFixed(2));
$('#invoice_subtotal').val(subT.toFixed(2));
$('.invoice-discount').text(disc.toFixed(2));
$('#invoice_discount').val(disc.toFixed(2));
if($('.invoice-vat').attr('data-enable-vat') === '1') {
if($('.invoice-vat').attr('data-vat-method') === '1') {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
} else {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip + ((vat / 100) * withShip)).toFixed(2));
$('#invoice_total').val((withShip + ((vat / 100) * withShip)).toFixed(2));
}
} else {
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
}
}
function actionAddProduct(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_add_product").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#add_product").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
function actionCreateInvoice(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_create_invoice").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#create_invoice").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
console.log(data);
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
});

Jquery Close autoComplete list

I have the following JQuery to display an autocomplete list:
var displayNum = 10;
var pointer = displayNum;
function DelegateSearch(txtBox)
{
$("#" + txtBox).attr("placeholder", "Search by Last Name");
$(".ajaxcompanyRefreshImage").attr("src", "/images/refresh.jpg");
$(".ajaxcompanyRefreshImage").hide();
$("#" +txtBox).parents().find('.ajaxcompanyRefreshImage').click(function () { $("#" +txtBox).autocomplete("search"); });
$("#" +txtBox).dblclick(function () { $(this).autocomplete("search"); });
$("#" +txtBox).autocomplete({
change: function (event, ui) {
if ($(this).val() == '') {
$(this).parents().find('.ajaxcompanyRefreshImage').hide();
}
},
close: function (event, ui) {
return false;
},
select: function (event, ui) {
var addr = ui.item.value.split('-');
var label = addr[0];
var value = addr[1];
value += addr[2];
if (label == null || label[1] == null ||(label.length < 1 && value == '' && value.length < 1)) {
$(this).autocomplete("option", "readyforClose", false);
}
else {
if (value[1]!= 0) {
$(this).autocomplete("option", "readyforClose", true);
delegateSearchPostBack(value, label, txtBox);
}
}
return false;
},
response: function (event, ui) {
var more = { label : "<b><a href='javascript:showmoreNames();' id='showmore'>Show more Names...</a></b>", value: '' };
ui.content.splice(ui.content.length, 0, more);
},
open: function(event, ui) {
showmoreNames();
},
search : function (event, ui) {
if ($(this).val().length < 3) {
$(this).parents().find('.ajaxcompanyRefreshImage').hide();
return false;
}
$(".ui-menu-item").remove();
},
source: function (request, response) {
$.ajax({
url: "/ajax/ajaxservice.asmx/GetDelegateListBySearch",
data: "{ prefixText: " + "'" +request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
return data; },
minLength: 2,
success: function (data) {
pointer = displayNum;
response($.map(data.d, function (val, key) {
return {
label: DelegateSearchMenulayout(key, val),
value: val
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {}
});
}
});
}
function DelegateSearchMenulayout(key, val) {
var net = '';
var userData = val.split('-');
var table = "<table width=350px' style='border-bottom-style:solid;' class='menutable'>";
table += "<tr><th width='300px'></th>";
table += "<tr><td><b>" + userData[1] + "" + userData[2] + "</b></td></tr>";
table += "<tr><td>" + userData[4] + " - " + userData[3] + "</td></tr>";
table += "</table>";
return table;
}
function delegateSearchPostBack(userName, userId, txtBox) {
$("#" + txtBox).autocomplete("destroy");
$("#" + txtBox).val(userId +"-" + userName );
pointer = displayNum;
__doPostBack(txtBox, "");
}
function showmoreNames() {
$(".menutable").each(function (index) {
if (index >= pointer) {
$(this).parent().hide();
}
else {
$(this).parent().show();
}
});
if ($(".menutable").length <= pointer) {
$("#showmore").attr("href", "javascript: function () {return false;}");
$("#showmore").text("End of Users");
}
else pointer += displayNum;
}
It displays 10 names by default. If the list is longer, "Show more names" is displayed on click of which,10 more names are displayed. With the initial 10 names, the JQuery works perfect.When I click outside or hit ESC, the list of names disappears. But with a longer list, when I click on Show More Names, a longer list is displayed but on click of ESC or clicking outside the list, it does not disappear! How can I make this work?
I tried the following solution:
how to make the dropdown autocomplete to disappear onblur or click outside in jquery?
But with this solution, the list disappears when I click on Show More!
$(document).bind('click', function (event) {
// Check if we have not clicked on the search box
if (!($(event.target).parents().andSelf().is('#showmore'))) {
$(".ui-menu-item").remove();
}
});
The above worked. I did an additional check on document click whether the option 'Show More' is clicked. The has id= 'showmore'. Hence checking if user did not click on it.

ajax() call in javascript function

i have a jquery .click() function that executes an .ajax() method call
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value") ; //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
// alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
// alert(mediaID);
//ajax query to get link and excute code to launch music
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
when the .ajax() method executes succesfully it calls a javascript function
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
as you can see i have an .ajax() method inside my javascript function, is this possible?
I am creating loop that starts on the finish listener of the soundmanager object. So when I need to make the ajax call to get he next url I need. If my way isnt correct can you please tell me what is the best way to accomplish what i am trying to do.
Think it's fine but i would make a separate function for the ajax call so you dont need to duplicate the code twice. Easier to maintain.
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value"); //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
//alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
//alert(mediaID);
//ajax query to get link and excute code to launch music
getAudio(mediaID);
}
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
getAudio(mediaId);
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
function getAudio(mediaID) {
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
});
}

Categories

Resources