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
Related
Down there is my button n function for that button in php, how to add disable button for 30 mins after clicking on it? I need help for it because im still newbie on php coding..
<button class="btn btn-primary" style="width: 200px; outline: none;" id="testar" onclick="enviar()">START</button>
This my function:
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var ed = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
var sec = $("#sec").val();
$.ajax({
url: 'g3api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("Approved")) {
removelinha();
ap++;
aprovadas(resultado + "");
}else if(resultado.match("CCN")) {
removelinha();
ed++;
edrovadas(resultado + "");
}else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(ed) + parseInt(rp);
$('#cLive').html(ap);
$('#cWarn').html(ed);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cWarn2').html(ed);
$('#cDie2').html(rp);
}
});
}, 5000 * index);
});
}
function aprovadas(str) {
$(".aprovadas").append(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").append(str + "<br>");
}
function edrovadas(str) {
$(".edrovadas").append(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
function iloveyou(){
alert('PEKPEK')}
</script>
My question is: How to make the button disabled for 30 minutes after it's clicked?
button.addEventListener('click', () => {
if (localStorage.getItem('clicked') === 'true') return;
localStorage.setItem('clicked', 'true');
button.disabled = true;
setTimeout(() => {
localStorage.removeItem('clicked');
button.disabled = false;
}, 60000 * 10);
});
Basically what I want to do is, if GATE1 is selected from the dropdown menu then run evinar() function on button click, otherwise if GATE2 is selected from the dropdown menu then run evinar2 function on button click.
<select name="gates" id="gates">
<option value="gates">GATES</option>
<option value="1">GATE1</option>
<option value="2">GATE2</option>
</select>
<button class="btn btn-primary" style="width: 360px; outline: none;" id="testar" onclick="enviar()">➤「Start」</button>
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
$.ajax({
url: 'api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("#Approved")) {
removelinha();
ap++;
aprovadas(resultado + "");
} else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
}
});
}, 2500 * index);
});
}
function evinar2() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
$.ajax({
url: 'api2.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("#Approved")) {
removelinha();
ap++;
aprovadas(resultado + "");
} else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
}
});
}, 2500 * index);
});
}
</script>
There are multiple ways to go around this depending on how you want to tackle it. If this button click is the same that would submit your form, then might want to serialize the form data, and get the value of this field. Look into .serializeArray() from jQuery
Otherwise, you'd select the field by id and get its value. Typically, I'd create a third function that is triggered on click. The new function would get the field value and then call either functions depending on the value. Check out the Codepen.
<select name="gates" id="gates">
<option value="gates">GATES</option>
<option value="1">GATE1</option>
<option value="2">GATE2</option>
</select>
<button onclick="functionSelector()">➤「Start」</button>
<script>
// this function will route your request
function functionSelector() {
var e = document.getElementById("gates");
var value = e.options[e.selectedIndex].value;
if(value === "1")
enviar();
else if (value === "2")
evinar2();
else
unknownOption();
}
function enviar() {
alert('enviar')
}
function evinar2() {
alert('enviar 2')
}
function unknownOption () {
alert('Unexpected answer')
}
</script>
As you're already using jQuery, you could do it like this:
$(document).ready(function() {
$("select").on("change", function() {
if ($(this).children("option:selected").val() == 1) {
evinar();
}
else if ($(this).children("option:selected").val() == 2) {
evinar2();
}
});
});
I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}
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");
}
});
}
}
});
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.