Jquery Close autoComplete list - javascript

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.

Related

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

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();
});

Form Validation with sum of fields

I'm trying to get this validation code to work. I only want the user to be able to add to the cart when the sum of the fields is equal to 7, if it does not equal 7 then an error should be shown.
Any help would be great as I can't see where I need to change it.
JSFiddle
$('#button-cart').on('click', function() {
var $fieldsSet = $('div.validateFields');
var MaxSelectionNum = "7"
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$fieldsSet.find('input[name^="option-quantity"]').each(function() {
sum += parseInt($(this).val()) || 0;
});
// Set the sum
$fieldsSet.find('.sum').val(sum);
var allSumEqualCustomDesc = true;
if (allSumEqualCustomDesc) {
$("div.errorQuantity").html("Please select 7 meals").show();
} else {
$("div.errorQuantity").hide();
};
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'number\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);
$('html, body').animate({
scrollTop: 0
}, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
}
);
Here are two ways of doing it:
(Not added the AJAX code but i've commented where it should go)
Example 1:
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").hide();
// AJAX SHOULD GO HERE!
}
});
JSFIDDLE EXAMPLE
Example 2: (Closer to your original code)
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
// Set the sum
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
$(".sum").html(sum);
if ($(document).find('.sum').val(sum) > MaxSelectionNum)
{
$(".errorQuantity").hide();
// AJAX SHOULD GO HERE!
}
else
{
$(".errorQuantity").html("Please select 7 meals").show();
}
});
UPDATED JSFIDDLE
UPDATED (TALKED ABOUT IN COMMENT SECTION):
JSFIDDLE EXAMPLE

closure compiler give error when complie jquery .post function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
It give this error "JSC_TRAILING_COMMA: Parse error. IE8 (and below) will parse trailing commas in array and object literals incorrectly. If you are targeting newer versions of JS, set the appropriate language_in option. at line 216 character 46 needID: needID," when i compile following javascript code.please help me to find what is wrong.
$(document).ready(function () {
var quantityPattern;
var datePattern;
var currentNeedDate;
var currentQuantity;
var currentNDescription;
var currentNName;
$(".save").hide();
$(".cancel").hide();
$(".needID").hide();
$(".addNow").hide();
$(".newData").hide();
$(".cancelAddData").hide();
quantityPattern = new RegExp(/^[0-9]*$/);
//check formatted as YYYY/MM/DD or YYYY-MM-DD
datePattern = new RegExp(/^(?!(?![02468][048]|[13579][26]00)..(?!(?!00)[02468][048]|[13579][26])...02.29)\d{4}([\/-])(?=0.|1[012])(?!(0[13578]|1[02]).31|02.3)\d\d\1[012]|3[01]$/);
//add button start-------------------------------------------------------------------------------------------------------------------------------
$(".add").click(function () {
$(".newData").show();
$(".addNow").show();
$(".cancelAddData").show()
$(this).hide();
});
//add button end-------------------------------------------------------------------------------------------------------------------------------
//cancelAddData button start -----------------------------------------------------------------------------------------------------------------------------
$(".cancelAddData").click(function () {
$(".newData").val("");
$(".add").show();
$(".newData").hide();
$(".addNow").hide()
$("#inputState").text("");
$(this).hide();
});
//cancelAddData button end -----------------------------------------------------------------------------------------------------------------------------
//addNow button start-------------------------------------------------------------------------------------------------------------------------------
$(".addNow").click(function () {
var nName = $(".newData.nName").val();
var nDescription = $(".newData.nDescription").val();
var quantity = $(".newData.quantity").val();
var needDate = $(".newData.needDate").val();
if ((nName === "") || (nDescription === "") || (quantity === "") || (needDate === ""))
{
$("#inputState").text("Enter data").css("color", "red");
return;
}
else if (!quantityPattern.test(quantity))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
else if (!datePattern.test(needDate))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
$("#inputState").text("");
$.post("AddShopNeedRqst",
{
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Update data successfully").css("color", "green").show().fadeOut(2000);
location.reload();
}
else
{
$("#inputState").text("record not updated ").css("color", "red").show().fadeOut(2000);
location.reload();
}
});
$(".newData").val("");
$(".add").show();
$(".newData").hide();
$(".cancelAddData").hide();
$(this).hide();
});
//addNow button end-------------------------------------------------------------------------------------------------------------------------------
//edit button start -----------------------------------------------------------------------------------------------------------------------------
$(".edit").click(function () {
var nName = $(this).parents("tr").find(".nName").html();
var nDescription = $(this).parents("tr").find(".nDescription").html();
var quantity = $(this).parents("tr").find(".quantity").html();
var needDate = $(this).parents("tr").find(".needDate").html();
currentNName = nName;
currentNDescription = nDescription;
currentQuantity = quantity;
currentNeedDate = needDate;
$(this).parents("tr").find(".nName").html('<input type="text" value="' + nName + '">');
$(this).parents("tr").find(".nDescription").html('<input type="text" value="' + nDescription + '">');
$(this).parents("tr").find(".quantity").html('<input type="text" value="' + quantity + '">');
$(this).parents("tr").find(".needDate").html('<input type="text" value="' + needDate + '">');
$(this).parents("tr").find(".save").show();
$(this).parents("tr").find(".cancel").show();
$(".edit").prop("disabled", true);
});
//edit button end -----------------------------------------------------------------------------------------------------------------------------
//cancel button start -----------------------------------------------------------------------------------------------------------------------------
$(".cancel").click(function () {
$(this).parents("tr").find(".nName").html(currentNName);
$(this).parents("tr").find(".nDescription").html(currentNDescription);
$(this).parents("tr").find(".quantity").html(currentQuantity);
$(this).parents("tr").find(".needDate").html(currentNeedDate);
$(this).hide();
$(this).parents("tr").find(".save").hide();
$(".edit").prop("disabled", false);
$("#inputState").text("");
});
//cancel button end -----------------------------------------------------------------------------------------------------------------------------
//save button start -----------------------------------------------------------------------------------------------------------------------------
$(".save").click(function () {
var needID = $(this).parents("tr").find(".needID").html();
var nName = $(this).parents("tr").find(".nName").children("input").val();
var nDescription = $(this).parents("tr").find(".nDescription").children("input").val()
var quantity = $(this).parents("tr").find(".quantity").children("input").val();
var needDate = $(this).parents("tr").find(".needDate").children("input").val();
if ((nName === "") || (nDescription === "") || (quantity === "") || (needDate === ""))
{
$("#inputState").text("Enter data").css("color", "red");
return;
}
else if (!quantityPattern.test(quantity))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
else if (!datePattern.test(needDate))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
$("#inputState").text("");
$.post("SaveEditShopNeedRqst",
{
needID: needID,
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Update data successfully").css("color", "green").show().fadeOut(2000);
}
else
{
$("#inputState").text("record not updated ").css("color", "red").show().fadeOut(2000);
location.reload();
}
});
$(this).parents("tr").find(".nName").html(nName);
$(this).parents("tr").find(".nDescription").html(nDescription);
$(this).parents("tr").find(".quantity").html(quantity);
$(this).parents("tr").find(".needDate").html(needDate);
$(this).hide();
$(".edit").prop("disabled", false);
$(".cancel").hide();
});
//save button end ----------------------------------------------------------------------------------------------------
//delete button start -----------------------------------------------------------------------------------------------------------------------------
$(".delete").click(function () {
var needID = $(this).parents("tr").find(".needID").html();
$(this).parents("tr").remove();
$.post("DeleteShopNeedRqst",
{
needID: needID,
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Delete data successfully").css("color", "green").fadeOut( 3000, "linear");
}
else
{
$("#inputState").text("record not deleted ").css("color", "red").fadeOut( 3000, "linear");
location.reload();
}
});
});
//delete button end -----------------------------------------------------------------------------------------------------------------------------
});
You have an extra bracket that should be removed:
$.post("AddShopNeedRqst", {
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
}, function (data, status) {
} //<-- The extra bracket has to be removed.
});
UPDATE
With your code update, the there's an error in the object posted to DeleteShopNeedRqst:
$.post("DeleteShopNeedRqst",
{
needID: needID, //<-- The comma has to be removed
},

Jquery Autocomplete not supported by keyboard

Autocomplete is not working for keyboard keys but it is working for mouse.i couldnot select item by arrow keys and enter key.
Here is my code. please suggest me any idea. and how to change my selected item background colour in input field?
var triggered = false;
var trigger = "#";
jQuery(".inputbox").autocomplete({
source: function( request, response ) {
var term = request.term;
jQuery.ajax({
url: "/home/friends?q="+term,
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
// alert(item.value);
return {
label: item.name,
value: item.name }
}));
}
});
},
search: function() {
if (!triggered) {
return false;
}
},
select: function(event, ui) {
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) +
ui.item.value;
triggered = false;
return false;
},
focus: function() { return false; },
delay: 0,
minLength: 0,
allowNewTags: false
}).bind("keyup", function() {
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
}
else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
I recommend to use https://github.com/ghiden/angucomplete-alt. It have this feature implemented by default.

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