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

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
},

Related

I want to add a loading png in LiveSearch

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

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

jquery click send function wont work only update the same field

I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

jQuery improve table iterator

I have a table containing in every row one cell inside which is checkbox and label for that checkbox.
What I'm trying to do it to hide rows based on inputed text.
Basically this is list on names and I want to filter/hide those that don't contain entered text.
This is my function:
$(function () {
$('#user_name').keyup(function () {
if ($.trim($('input#user_name').val()) == '') {
$('table.myList >tbody >tr').each(function (index, value) {
$(this).css("display", "block");
});
} else {
$('table.myList >tbody >tr').each(function (index, value) {
if ($(this).find('td > label').length > 0) {
if ($(this).find('td > label').html().toLowerCase().indexOf($.trim($('input#user_name').val()).toLowerCase()) >= 0) {
$(this).css("display", "block");
} else {
$(this).css("display", "none");
}
}
});
}
});
});
This code works, if my table has 40 records its fast, but when I increment list to 500 it slows down and crashes my browser after time.
I'm looking for a way to improve this code to work faster.
Here is link to mock-up code: http://jsfiddle.net/gGxcS/
==UPDATE==
Here is my final solution based on answers of #scessor and #nnnnnn:
$(function () {
var $tableRows = $('table.myList tr');
var lastInput = '';
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if(lastInput==sValue) return;
if (sValue == '') {
$tableRows.show();
} else {
$tableRows.each(function () {
var oLabel = $(this).find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
}
});
lastInput=sValue;
}
});
$('img.removeSelections').click(function () {
$('table.myList input[type="checkbox"]').prop("checked", false);
})
});
Can you test this code (with lot of elements)?
$(function () {
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if (sValue == '') {
$('table.myList tr').show();
} else {
$('table.myList tr').each(function() {
var jThis = $(this);
var oLabel = jThis.find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
jThis.show();
} else {
jThis.hide();
}
}
});
}
});
});
Don't call functions with same parameters twice (e.g. $.trim($('input#user_name').val());).
Use short selectors.
Use jquery each only if necessarry (e.g. don't needed here: $('table.myList >tbody >tr').each(function (index, value) {).
=== UPDATE ===
If somebody holds backspace to long, it will set all trs visible again and again. To prevent this you could check, if the last value is equal to the current value. If true, do nothing.
=== UPDATE ===
To uncheck all checkboxes, it depends on your jQuery version.
With jQuery 1.6 and higher:
$('table.myList input[type="checkbox"]').prop("checked", false);
Before:
$('table.myList input[type="checkbox"]').attr("checked", false);
I'd suggest that you cache your jQuery objects - given that you want to process on every keystroke I'd cache the table rows object outside of the keyup handler. Also, don't call functions inside the .each() loop when you can call them once outside - e.g., no need to be calling $.trim($('input#user_name').val()).toLowerCase() on every .each() iteration.
$(function () {
var $tableRows = $('table.myList >tbody >tr');
$('#user_name').keyup(function () {
var searchStr = $.trim($('input#user_name').val()).toLowerCase();
if (searchStr === '') {
$tableRows.css("display", "block");
} else {
$tableRows.each(function (index, value) {
var $this = $(this),
$label =$this.find('td > label');
if ($label.length > 0) {
if ($label.html().toLowerCase().indexOf(searchStr) >= 0) {
$this.css("display", "block");
} else {
$this.css("display", "none");
}
}
});
}
});
});
Demo: http://jsfiddle.net/gGxcS/3/

Categories

Resources