1. Open the docs in new window.
1.Open the docs in new window:========================================================================
viewwin = window.open(imgsrc, 'viewwin', 'width=1000,height=1000');
2. Restricting for alphabet entry only
==========================================function onlyAlphabets(e, t, maxLen) {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if (t.value.length > (maxLen - 1) && charCode !== 8) {
return false;
}
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 8))
return true;
else
return false;
}
https://www.sitepoint.com/trimming-strings-in-javascript/
http://stackoverflow.com/questions/4753823/jquery-prevent-enter-key
http://dmauro.github.io/Keypress/
http://stefangabos.ro/jquery/zebra-datepicker/
https://latesthackingnews.com/2015/10/16/javascript-cheat-sheet-free-download/
https://www.cheatography.com/davechild/cheat-sheets/javascript/pdf/
https://www.cheatography.com/
http://www.jquery-az.com/
http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-get-values-of-selected-checboxes
http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false?rq=1
http://viralpatel.net/blogs/tutorial-handle-browser-events-using-jquery-javascript-framework/
3. How to f5 control refresh in jQuery
====================================================step-1:Write code in jQuery file
//#region handling f5(refresh click)
jQuery(document).keydown(function (e) {
if ((e.which == 116) || (e.keyCode == 116)) {
e.preventDefault();
alert("Hi, I got called from jQuery");
RedirectToScanGateTokenPage();
return false;
}
});
step-2: Write in aspx
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<script type="text/javascript">
jQuery(document).ready(function () {
alert("Hi, I got called from aspx");
ReLoadHtmlPage('#divPageID', pathToPage);
});
</script>
4. How to fully control browser back for jQuery mobile
=====================================================//#region Method executes on browser back
jQuery(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
event.preventDefault()
jQuery(document).unbind();
jQuery(window).unbind();
closeButton_Click();
}
});
5. Partial ID Selector
==============================jQuery("[id$=" + iconID + "]")
6. How to know whether element has been found using find in jQuery
=================================================1. jQuery(this).find("input[type = text]").length > 0 here length 0 represents input type text is not available under this object.
2. http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element
7. How to use camera for all browser using jQuery.
https://github.com/jhuckaby/webcamjs8. How to trim some specified characters using jQuery.
function TrimCharactersFromMaterialNum(materialNumber) {materialNumber = jQuery.trim(materialNumber);
var lastCount = materialNumber.length;
for (var count = 0; count < lastCount; count++) {
if (materialNumber.charAt(0) === "c" || materialNumber.charAt(0) === "0")
materialNumber = materialNumber.slice(1, materialNumber.length);
}
return materialNumber;
}
9. How to clear all textboxes at one shot.
jQuery("#txtValue,#txtQuality,#txtTimeStamp,#txtDisplayName").val("");10. Method to get the Parameters from QueryString.
function getParameterByName(name) {name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
11. How bind into dropdown list from taking the value from enum and text from global resource file.
string[] enumServerType = Enum.GetNames(typeof(MyEnums.myenums));foreach (string item in enumServerType)
{
ListItem listItem = new ListItem((String)GetGlobalResourceObject("myGlobal_Resource", item), item);
drpType.Items.Add(listItem);
}
drpType.Items.Insert(0, new ListItem(Language_Resources.myGlobal_Resource.selectType, "0"));
12. jQuery MultiSelect.
http://stackoverflow.com/questions/4753407/jquery-multiselect-drop-down-menu
https://github.com/wenzhixin/multiple-select
http://wenzhixin.net.cn/p/multiple-select/docs/#the-refresh
13. Javascript Validation.
Email validation:
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var filteremail = filter.test(mailId);
if (filteremail) {}
For blocking special character:
$(document).on('change', ':text', function () {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var filteremail = filter.test(mailId);
if (filteremail) {}
For blocking special character:
$(document).on('change', ':text', function () {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var hostNameFormat = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/ig;
if (ipformat.test(jQuery.trim(jQuery("#txtDeviceIPAddress").val())) || hostNameFormat.test(jQuery.trim(jQuery("#txtDeviceIPAddress").val()))) {
deviceInformation.DeviceIPAddress = jQuery("#txtDeviceIPAddress").val().trim();
}
else {
errorMsg = errorMsg + " *" + languageResource.resMsg_PleaseEnterValidIPAddressOrHostName + "<br>";
isValid = false;
}
var txtPortNumber = jQuery.trim(jQuery("#txtPortNumber").val());
if ((txtPortNumber.length == 0) || !(jQuery.isNumeric(txtPortNumber)) || (txtPortNumber > 65535)) {
errorMsg = errorMsg + " *" + languageResource.resMsg_PleaseEnterValidPortNumber + "<br>";
isValid = false;
}
14. For handling single quote for binding javascript method.
=======================================================string orderType = orderTypeInfo.OrderTypeCode.Replace("'","\\'");
15. <br> to separated by comma
=======================================================var reg = /<br *\/?>/gi;
var temp = tempBulkIDHDescList.replace(reg, ',');
16. Under one div count no of input text boxes or input type
=======================================================var ctlCount = 0;
jQuery("#textContent input").each(function () {
ctlCount++;
});
17. Handle multiple popup.
=======================================================http://stackoverflow.com/questions/13649459/twitter-bootstrap-multiple-modal-error
// Since confModal is essentially a nested modal it's enforceFocus method
// must be no-op'd or the following error results
// "Uncaught RangeError: Maximum call stack size exceeded"
// But then when the nested modal is hidden we reset modal.enforceFocus
var enforceModalFocusFn = $.fn.modal.Constructor.prototype.enforceFocus;
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
$confModal.on('hidden', function() {
$.fn.modal.Constructor.prototype.enforceFocus = enforceModalFocusFn;
});
$confModal.modal({ backdrop : false });
18. To add style using jQuery
=======================================================jQuery(this).css("border-color", "red");
19. To Check the length of text area
=======================================================$(function () {
$("textarea[maxlength]").bind('input propertychange', function () {
var maxLength = $(this).attr('maxlength');
//I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
//Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
var newlines = ($(this).val().match(/\n/g) || []).length
if ($(this).val().length + newlines > maxLength) {
$(this).val($(this).val().substring(0, maxLength - newlines));
}
})
});
20. Validating new password with atleast one number and one character and minimum 6 digit and no special character
======================================================
if (!password.match(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/)) {errorMessage = errorMessage + " " + languageResource.resMsg_PasswordValidation + "<br/>";
isValid = false;
}
using System.Text.RegularExpressions;
Match passwordMatch = Regex.Match(password, @"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$"); //Validating new password with atleast one number and one character and minimum 6 digit and no special character.
passwordMatch.Success == true
21. Handeling special character while binding javascript method
================================================================\"" + ommu + "\"
22. To Check the javascript object is empty
================================================================jQuery.isEmptyObject(obj) == false
23. To apply any class to even rows
================================================================jQuery("#tblSelectedStations tr:even").addClass("alt");
24. How to filter an array using grep in javascript.
http://api.jquery.com/jquery.grep/25. $(document).ready and window.onload() difference
http://www.dotnetbull.com/2013/08/document-ready-vs-window-onload.html
26. Jquery file loading error
If any small error anywhere in the file then that file wont load and work. And this apply to all kind of JS files.
27. Table level jQuery tricks.
1. orgTableHead = jQuery('#multiplePlantCodetable').find('th:eq(2),th:eq(3)');
orgTableDiv = jQuery("#" + tBodyForMultiplePlants).find('td:eq(2),td:eq(3)');
jQuery(orgTableHead).show();
jQuery(orgTableDiv).show();
2. var rowCount = $("#Table1")[0].rows.length; this is for getting only parent rows
3. var rowCount = $("#Table1 > tbody > tr").length;
3. jQuery("#" + jQuery.WarehouseNamespace.PagerData.LoadControlID + " tr").each(function () {
// pageRowCount++;
// });
this is for getting parent rows with child rows coming within table
4. How to get the last row td contains text box value.
var lastGroupset = jQuery("#" + tableBody + " tr:last").find("input[type = text]").attr("groupid");
jQuery("#" + tableBody + " tr").each(function () {
if (jQuery("#" + this.id.replace("trPhaseParameter", "spnGroupFrequency")).attr("groupFrequencyValue") != undefined) {
lastFrequencySet = jQuery("#" + this.id.replace("trPhaseParameter", "spnGroupFrequency")).attr("groupFrequencyValue");
}
if (lastGroupset != undefined && lastGroupset >= 0) {
if (jQuery(this).find("input[type = text]").length > 0 && (jQuery(this).find("input[type = text]").attr("groupid") != undefined) && (jQuery(this).find("input[type = text]").attr("groupid") == lastGroupset) && jQuery.trim(jQuery(this).find("input[type = text]").val()).length > 0) {
islastFrequencySetEntered = true;
}
}
});
5. https://datatables.net/reference/type/row-selector
6. How to filter rows of table as per rows attribute using jQuery
jQuery("#" + tableBody + " tr[groupFrequencyValue=" + groupFrequency + "]")
7. How to append rows from the last row id.
var additionIDHRowID = jQuery("#" + materialInfoTable + " tr[sampleLabelNumber=" + sampleLabelNum + "] :last").prop("id");
if (additionIDHRowID != undefined) {
jQuery("#" + additionIDHRowID).after(jQuery(this).find("AdditionParameterContent").text());
}
orgTableDiv = jQuery("#" + tBodyForMultiplePlants).find('td:eq(2),td:eq(3)');
jQuery(orgTableHead).show();
jQuery(orgTableDiv).show();
2. var rowCount = $("#Table1")[0].rows.length; this is for getting only parent rows
3. var rowCount = $("#Table1 > tbody > tr").length;
3. jQuery("#" + jQuery.WarehouseNamespace.PagerData.LoadControlID + " tr").each(function () {
// pageRowCount++;
// });
this is for getting parent rows with child rows coming within table
4. How to get the last row td contains text box value.
var lastGroupset = jQuery("#" + tableBody + " tr:last").find("input[type = text]").attr("groupid");
jQuery("#" + tableBody + " tr").each(function () {
if (jQuery("#" + this.id.replace("trPhaseParameter", "spnGroupFrequency")).attr("groupFrequencyValue") != undefined) {
lastFrequencySet = jQuery("#" + this.id.replace("trPhaseParameter", "spnGroupFrequency")).attr("groupFrequencyValue");
}
if (lastGroupset != undefined && lastGroupset >= 0) {
if (jQuery(this).find("input[type = text]").length > 0 && (jQuery(this).find("input[type = text]").attr("groupid") != undefined) && (jQuery(this).find("input[type = text]").attr("groupid") == lastGroupset) && jQuery.trim(jQuery(this).find("input[type = text]").val()).length > 0) {
islastFrequencySetEntered = true;
}
}
});
5. https://datatables.net/reference/type/row-selector
6. How to filter rows of table as per rows attribute using jQuery
jQuery("#" + tableBody + " tr[groupFrequencyValue=" + groupFrequency + "]")
7. How to append rows from the last row id.
var additionIDHRowID = jQuery("#" + materialInfoTable + " tr[sampleLabelNumber=" + sampleLabelNum + "] :last").prop("id");
if (additionIDHRowID != undefined) {
jQuery("#" + additionIDHRowID).after(jQuery(this).find("AdditionParameterContent").text());
}
Loop through rows having particular type ID
---------------------------------------------
jQuery("#" + jQuery.ExternalWarehouseNamespace.LoadControlID + " > tr[id*='trOrderDetails']").length;
---------------------------------------------
jQuery("#" + jQuery.ExternalWarehouseNamespace.LoadControlID + " > tr[id*='trOrderDetails']").length;
Nice jQuery Table Creating link
--------------------------------------------------------------
https://www.htmlgoodies.com/beyond/css/working_w_tables_using_jquery.html
How to loop through checkbox contained in each row of a table
------------------------------------------------------------------------------
jQuery("#" + jQuery.OPCTagNameSpace.PagerData.LoadControlID + " tr input:checkbox").each(function () {
28. CK EDITOR.
http://docs.ckeditor.com/#!/guide/dev_basics
29. Ddhtml tutorial.
http://docs.dhtmlx.com/scheduler/how_to_start.html
http://docs.dhtmlx.com/scheduler/timeline_view.html
http://docs.dhtmlx.com/scheduler/api__scheduler_onbeforeeventchanged_event.html
http://docs.dhtmlx.com/scheduler/timeline_view.html
http://docs.dhtmlx.com/scheduler/api__scheduler_onbeforeeventchanged_event.html
30. Video lectures
http://tutorialehtml.com/en/html-tutorial-embed-video/
http://sachinchoolur.github.io/lightslider/
http://www.codeproject.com/Articles/1006192/JavaScript-Summary
http://sachinchoolur.github.io/lightslider/
http://www.codeproject.com/Articles/1006192/JavaScript-Summary
31. JavaScript: Node Type, Node Name, Node Value
http://xahlee.info/js/js_get_node_info.html
32. How to Jstree in javascript.
https://www.jstree.com/plugins/
33. How to check a text is NaN.
http://stackoverflow.com/questions/9311542/jquery-if-value-is-nan
33. How to check a text is NaN.
http://stackoverflow.com/questions/9311542/jquery-if-value-is-nan
34. How to clear the file uploader value in all browser.
if (navigator.userAgent.search("MSIE") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
control.replaceWith(control = control.clone(true));
else
jQuery("#" + uploadFile).val('');
control.replaceWith(control = control.clone(true));
else
jQuery("#" + uploadFile).val('');
PadLeft(jQuery.trim(materialNumber), 18, '0')
32. How to make phase flow diagrams in javascript.
https://knsv.github.io/mermaid/#mermaid
https://knsv.github.io/mermaid/#mermaid
parseFloat(Quantity1 - Quantity2).toFixed(3);
32. How to restrict entry with positive and 3 decimal
1.
onkeypress="return isDecimalCheck(event,this);
function isDecimalCheck(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 45) {//for not allowing - entry
if ((charCode != 45 || jQuery(element).val().indexOf('-') != -1) && (charCode != 46 || jQuery(element).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
else if (charCode == 45) {
// Set minus character at the beginning of the line
evt.preventDefault();
jQuery(element).val(String.fromCharCode(charCode) + jQuery(element).val());
return true;
}
else {
var dotPosition = jQuery(element).val().indexOf(".");
var cursorPosition = jQuery(element).val().slice(0, element.selectionStart).length;
if (dotPosition != -1 && cursorPosition > dotPosition) {
var splittedValue = (jQuery(element).val()).split(".");
if (splittedValue[1].length > 2) {
return false;
}
}
return true;
}
}
else
return false;
}
2.
onkeypress="return ValidateDecimalInput(this, event, 8, 2);"
function ValidateDecimalInput(ctrl, event, maxLength, maxPrecision) { var s = "^((?=.*\\d)\\d{1," + maxLength + "}(\\.\\d{0," + maxPrecision + "}?)?)$"; var regex = new RegExp(s); var key = String.fromCharCode(event.charCode); var value = jQuery(ctrl).val().trim(); var init = value.substring(0, event.target.selectionStart); var substr = value.substring(event.target.selectionStart); var final = init + key + substr; if (!regex.test(final)) { event.preventDefault(); return false; } }
32. How to call WCF Service from jQuery Ajax using Rest service.
jQuery.support.cors = true;
jQuery.ajax({
type: 'POST',
processData: true,
url: jQueryABC.RestServicePath + "/WCFService.svc/GetABCVAlues",
data: JSON.stringify(directVariableValuesToPass),
contentType: "application/json",
dataType: "json",
async: false,
success: function (json) {
32. How to use autogrow plugin in jQuery for growing text boxes as per text.
https://plugins.jquery.com/autogrow/
https://github.com/ultimatedelman/autogrow
http://jsfiddle.net/edelman/HrnHb/
33. Solution for modal over modal.
jQuery(document).on('show.bs.modal', '.modal', function (event) {
var zIndex = 1040 + (10 * jQuery('.modal:visible').length);
jQuery(this).css('z-index', zIndex);
setTimeout(function () {
jQuery('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
34. All Kind of validation in jQuery.
http://www.designchemical.com/blog/index.php/jquery/form-validation-using-jquery-and-regular-expressions/
35. How to check the text area length in jQuery. onkeypress="return ( this.value.length < 1000 );"
36. How use keyboard events in jQuery.
http://stackoverflow.com/questions/19347269/jquery-keypress-arrow-keys
37. JQuery Mobile Tutorial.
https://www.w3schools.com/jquerymobile/default.asp
http://demos.jquerymobile.com/1.1.2/docs/pages/page-anatomy.html
http://knockoutjs.com/examples/betterList.html
38. How to get the option of a dropdown from value in jQuery.
jQuery("#drpParameterUnit [value=" + value + "]").text();
39. How to make an ajax call in jQuery.
jQuery.ajax({
type: "POST",
url: pathtoService/GetTruckEntryInfo",
data: JSON.stringify({ value: value1 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) { },
error: function (request, error) { }
});
40. How to use foreach loop in jQuery using knockout.
ko.utils.arrayForEach(list, function (a) {
anotherList.push(a);
});
41. How to check the button is disabled or not before calling method in jQuery.
var attr = jQuery("#btnID").attr('disabled');
if (typeof attr !== typeof undefined && attr !== false) {
return;
}
42. How to disable all child elements in jQuery.
http://stackoverflow.com/questions/4838209/recursively-disabling-all-children-of-an-element
43. How to call a method when it is as a variable.
window[selectMethod](Parameters);Here selectMethod is a variable which is our method name.
44. TimeLine view jQuery framework library
http://visjs.org/examples/graph2d/15_streaming_data.html
http://visjs.org/examples/graph2d/15_streaming_data.html
http://visjs.org/docs/timeline/
45. Forming graph 2d, 3d from data using high charts.
https://www.highcharts.com/demo/line-time-series
How to put if coding in html using knockout
<table data-role="table" id="tabMaterialList" data-mode="column-toggle" class="ui-body-d ui-shadow ui-responsive media-table">
<thead class="media-table">
<tr class="ui-bar-d">
<th data-priority="1" style="width: 10%;">
</th>
<th data-bind="html: MaterialColumn" style="width: 30%;">
</th>
<th data-bind="html: BatchColumn,visible:batchColumnVisible" style="width: 30%;">
</th>
<th data-bind="html: QtyColumn" style="width: 30%;">
</th>
<th data-bind="html: UnitColumn" style="width: 30%;">
</th>
</tr>
</thead>
<tbody data-bind="foreach: viewFormModel.MaterialList">
<tr data-bind="attr: {onclick: 'javascript:SetMaterial(\'' + $index() + '\',true)'}">
<td style="width: 10%;">
</td>
<td data-bind="text: Material" style="width: 30%;">
</td>
<!-- ko {if: viewFormModel.batchColumnVisible} -->
<td id="tdMaterialBatch" data-bind="text: Batch" style="width: 30%;">
</td>
<!-- /ko -->
<td data-bind="text: Quantity" style="width: 30%;">
</td>
<td data-bind="text: Unit" style="width: 30%;">
</td>
</tr>
</tbody>
</table>
Knockout Section:
https://stackoverflow.com/questions/30286027/what-is-the-difference-between-root-and-parent
data-bind="css: $parent.ChangeBinBGClass(CountDays)"
NameSpace With Knockout
https://codepen.io/dustinpage/pen/Kwmgj
44. TimeLine view jQuery framework library
45. How to loop through key value pair in jQuery
for (var key in jQuery.OPCTagNameSpace.AccessRights) {
if (jQuery.OPCTagNameSpace.AccessRights[key] == data.d.OPCTagAccessRights) {
value = key;
}
}
46. How to check value avaiable in dropdown list or not
jQuery("#" + drpAccessRights).val("0");
if (jQuery("#" + drpAccessRights).find("option[value=" + value + "]").length > 0)//if available in dropdown values then only select
jQuery("#" + drpAccessRights).val(value);
var isGecko = (navigator.userAgent.indexOf("Gecko") != -1);
var isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != -1);
var isNav = (navigator.appName.indexOf("Netscape") != -1);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var isMac = (navigator.appVersion.indexOf("Macintosh") >= 0);
var isUx = (navigator.appVersion.indexOf("X11") >= 0);
var isChrome = (navigator.userAgent.toLowerCase().indexOf("chrome") != -1);
var isSafari = (navigator.userAgent.indexOf("Safari") != -1);
var browserName = navigator.appName;
-----------------------------------------------------
http://api.jquery.com/category/events/
Javascript all manipulations
-----------------------------------------------------
http://api.jquery.com/category/manipulation/
How to use dictionary in jQuery
-----------------------------------------------
function Dictionary() {
var dictionary = {};
this.setData = function (key, val) { dictionary[key] = val; }
this.getData = function (key) { return dictionary[key]; }
}
jQuery.Test.Dictionary = new Dictionary();
jQuery.Test.Dictionary.setData(index, data);
jQuery.Test.Dictionary.getData(index);
How to create icon tag and attach it to any other control
----------------------------------------------------------------------------------
var linkIcon = document.createElement('i');
linkIcon.setAttribute('class', "fa fa-link tiny-leftmargin");
jQuery(linkIcon).bind("click", function () {
alert("HI");
});
jQuery("#" + value.node.children[j]).append(linkIcon);
For Replacing all the same words in sentence in jQuery
----------------------------------------------------------------------------------- https://stackoverflow.com/questions/3214886/javascript-replace-only-replaces-first-match
Json Validator online
---------------------------------
https://jsonlint.com/
hasownproperty jquery example
----------------------------------------------
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
https://stackoverflow.com/questions/9396569/javascript-what-is-property-in-hasownproperty
Strict visibility check for checkbox
---------------------------------------------
if (jQuery("#" + checkBoxID).is(":visible") && jQuery("#" + checkBoxID).css('display') !== 'none') {
For Checking Password validation
----------------------------------------------------
if (jQuery.PasswordValidation.PwdContainLetter && !password.match(/([a-zA-Z])/)) {
pwdErrorMessage = pwdErrorMessage.length > 0 ? pwdErrorMessage + languageResource.resMsg_PasswordContainAtleastOneChar : pwdErrorMessage + languageResource.resMsg_PasswordShouldContainCharacter;
isValid = false;
}
if (jQuery.PasswordValidation.PwdContainSplCharacter && !password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) { // password contains at least one special character
pwdErrorMessage = pwdErrorMessage.length > 0 ? pwdErrorMessage + languageResource.resMsg_PasswordContainAtleastOneSplChar : pwdErrorMessage + languageResource.resMsg_PasswordShouldContainSplCharacter;
isValid = false;
}
if (!password.match(/([0-9])/)) { // password contains numbers
pwdErrorMessage = pwdErrorMessage = pwdErrorMessage.length > 0 ? pwdErrorMessage + languageResource.resMsg_PasswordContainAtleastOneNum : pwdErrorMessage + languageResource.resMsg_PasswordShouldContainOneNumber;
isValid = false;
}
For Looping through checked checkboxes
------------------------------------------------------------------------
jQuery("#divCheckBoxSiteList input[type=checkbox]:checked").each(function () {
checkboxValues.push(this.value);
});
Dropdown selected option attribute
----------------------------------------------------------------
jQuery('option:selected', "#drpCompanyDepartment").attr('accessvalue');
Dropdown scrolling code
---------------------------------------------------------------
function scrollUL(element) {
$(".site-label-height").animate({
scrollTop: jQuery(element).offset().top
}, 1000);
}
Code for preventing child checkbox call on click of parent div
------------------------------------------------------------------------------------------------------------
jQuery("#spnRolesCollection").append(jQuery("<div class='col-xs-6 p-a-0 bottom-gap' id='" + divID + "' onclick='SelectSiteRole(this.id, event);'><input class='pull-xs-left tiny-rightmargin push-down' type='checkbox' " + isChecked + " id='" + checkBoxID + "' roleID='" + value.RoleID + "' ><label class='pull-xs-left rightmargin' for= '" + checkBoxID + "'>" + value.RoleName + "</label></div>"));
jQuery("#spnRolesCollection").append(jQuery('<div></div>').attr({ class: 'col-xs-6 p-a-0 bottom-gap', id: divID, onclick: 'SelectSiteRole(this.id, event)' }).append(jQuery('<input>').attr({
type: 'checkbox', name: 'chklistitem', checked: isChecked, class: 'pull-xs-left tiny-rightmargin push-down', roleID: value.RoleID, id: checkBoxID })).append(jQuery('<label></label>').attr({ 'for': checkBoxID, class: 'pull-xs-left rightmargin' }).text(value.RoleName)));
POPOVER CODING
---------------------------------------------------------------
$("[data-toggle=popover]").each(function (i, obj) {
$(this).popover({
title: "Header",
trigger: "hover",
html: true,
content: function () {
var id = $(this).attr('id');
var siteID = $(this).attr('siteID');
var siteName = $(this).attr('siteName');
var userID = $(this).attr('userID');
return ViewSiteWiseRoles(siteID, siteName, userID);
}
});
});
How to disable onclick method of anchor tag
-------------------------------------------------------------------------------------
<a href="" id="btnRoleList" runat="server" enableviewstate="false" visible="false" style="position: relative;" data-html="true" onclick="return false;">
How to write code for keyup and keypress:
-------------------------------------------------------------------------------------
// onkeypress close form and redirect to specified page
jQuery(document).on("keyup", function (event) {
var eventCode = event.keyCode || event.which;
switch (eventCode) {
case 27: // 27 - Escape Key Event Raise
CallYourMethod();
break;
}
});
jQuery(document).on("keypress", function (event) {
var eventCode = event.keyCode || event.which;
switch (eventCode) {
case 49://on pressing 1
CallYourMethod();
break;
case 50://on pressing 2
CallYourMethod();
break;
}
});
Document object for browser holding what kind of information about the current loaded page?
---------------------------------------------------------------------------------------------------------------------------------------------document.cookie.split(';') document.location
How to block copy paste in textbox using jQuery
--------------------------------------------------------------------------------------------
$('#txtFromDate').keyup(function () {
if (this.value.match(/[^.]/g)) {
this.value = this.value.replace(/[^.]/g, ''); //^\d+\.\d{0,3}$
return false;
}
else {
return true;
}
});
What is %2C in a URL?
https://stackoverflow.com/questions/6182356/what-is-2c-in-a-urlHow to upload a file using Ajax:
------------------------------------------------------------------------------------------
var fileData = jQuery("#" + fileUpload).prop("files")[0];
var formData = new window.FormData();
formData.append("file", fileData);
jQuery.ajax({
type: "POST",
processData: false,
contentType: false,
url: "",
data: formData,
success: function (data) {
var responsMessage = data.split(',');
if (responsMessage[0] != "fail") {
var fileName = responsMessage[1];
TimerForFileUpload(fileName);
}
else {
ClearUpload();
jQuery("#lblUploadError").text(responsMessage[1]);
}
},
error: function (request, error) {
ClearUpload();
DisplayErrorMessage(request, error, "lblUploadError", languageResource.reMsg_FileUploadFail);
}
});
How to get month between two dates:
https://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript/21021069#21021069
function GetMonthDiffCount(fromDate, toDate) {
// Months between years.
var months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
// Months between... months.
months += toDate.getMonth() - fromDate.getMonth();
// Subtract one month if b's date is less that a's.
if (toDate.getDate() < fromDate.getDate()) {
months--;
}
return months <= 0 ? 0 : months;
}
How to remove multiple spaces from a string:
https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space
How to hide popover:
jQuery('.popover').remove();
To Apply Flip concept on any div:
Step-1: Add js plugin jquery.flip.min.js
Step-2: Add below js code in document.ready
jQuery("#mainDIv").flip({
trigger: 'manual',
speed: 1500
});
Step-3:Arrange your div for flip both side
<div id="mainDIv" class="col-xs-12 kanban-border p-a-1 m-b-1" style="overflow-y: auto;">
<div class="bottom-gap hide" id="divErrorInfo" style="overflow-y: auto; overflow-x: hidden;">
</div>
<div id="divBinUtilizationInfo" class="col-xs-12 m-b-1 hide">
<div id="divFront" data-bind="foreach: koModel.ValueList" class="front m-b-1 ">
</div>
<div id="divBack" data-bind="foreach: koModel.ValueList" class="back m-b-1 ">
</div>
</div>
<div id="divProgress" class="spinner-circle-big" style="display: none;"></div>
<p class="empty-page-content" style="margin-left: 0px !important;">
<marquee id="pageMarqueeText" direction="left" behavior="alternate" style="height: 60px; padding-top: 15px;">
"Empty message when no Data to display"
</marquee>
</p>
</div>
Step-3:Flip whenever your div needed for flip both side
jQuery("#mainDIv").flip('toggle');
http://nnattawat.github.io/flip/
https://github.com/nnattawat/flip
https://www.jqueryscript.net/animation/Creating-3D-Flip-Animations-with-jQuery-CSS3-Flip-js.html
To Apply Progress Bar on any div:
Step-(-1):Add js plugin bootstrap-progressbar.js
Step-0:<div id="progressbar" class="progress-info progress-striped progresscalendar active push-up text-center pull-xs-right"
style="margin-bottom: 0px; width: 150px;">
</div>
Step-1:jQuery('#progressbar').addClass("hide");
Step-2://Setting the loader strip max value
jQuery('#progressbar').progressbar({ maximum: 100 });
Step-3: var step = (loadedPageIndex / TotalRecords) * 100;
if (isNaN(step)) {
step = 100;
}
else {
step = Math.round(step, 2);
}
jQuery('#progressbar').progressbar('setPosition', step);
http://www.minddust.com/project/bootstrap-progressbar/demo/bootstrap-3-3-4/
https://stackoverflow.com/questions/21182058/dynamically-change-bootstrap-progress-bar-value-when-checkboxes-checked
How to remove the cross icon (clearing textbox) on textbox for IE:
https://stackoverflow.com/questions/14007655/remove-ie10s-clear-field-x-button-on-certain-inputs
input[type=text]::-ms-clear {
display: none;
}
OOPS oriented code for javascript:
var binUtilizationDashboardNamespace = (function () {
//Put All JS Code Here
return {
Write all method names which will get called from outside world
DownloadBillingReportExcel: DownloadBillingReportExcel,
ShowChargingType: ShowChargingType
}
})();
note:
1. All method has to be accessed by binUtilizationDashboardNamespace.MethodName for outside world.
2. Help in ambiguous method name.
https://www.w3.org/wiki/JavaScript_best_practices
Searchable drop-down:
Step-1:
Include select2.css,select2.js
Step-2: Apply select2() to your dropdown
$(document).ready(function () {
var querystring = $.QueryString["id"];
if (querystring != undefined && querystring != "") {
}
jQuery("#drpSOPIdentifier").select2();
});
https://select2.org/getting-started/installation
https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.js
Auto Complete code for jQuery mobile:
http://demos.jquerymobile.com/1.4.5/listview-autocomplete/#&ui-state=dialog
http://jsfiddle.net/rossmartin/ZNGxm/
<form class="ui-filterable">
<input id="autocomplete-input" data-type="search" placeholder="Search cars...">
</form>
<ul data-role="listview" data-filter="true" data-filter-reveal="true" data-input="#autocomplete-input">
<li><a href="#">Acura</a></li>
<li><a href="#">Audi</a></li>
<li><a href="#">BMW</a></li>
<li><a href="#">Cadillac</a></li>
<li><a href="#">Chrysler</a></li>
<li><a href="#">Dodge</a></li>
<li><a href="#">Ferrari</a></li>
<li><a href="#">Ford</a></li>
<li><a href="#">GMC</a></li>
<li><a href="#">Honda</a></li>
<li><a href="#">Hyundai</a></li>
<li><a href="#">Infiniti</a></li>
<li><a href="#">Jeep</a></li>
<li><a href="#">Kia</a></li>
<li><a href="#">Lexus</a></li>
<li><a href="#">Mini</a></li>
<li><a href="#">Nissan</a></li>
<li><a href="#">Porsche</a></li>
<li><a href="#">Subaru</a></li>
<li><a href="#">Toyota</a></li>
<li><a href="#">Volkswagen</a></li>
<li><a href="#">Volvo</a></li>
</ul>
How to trigger a change drop-down method using jQuery:
jQuery("#drpYard").val(yardLocationInfo.YardID).trigger('change')
Javascript nice tutorials:
https://www.quackit.com/javascript/tutorial/how_to_enable_javascript.cfm
Date Time functions:
https://www.quackit.com/javascript/javascript_date_and_time_functions.cfm
How to click a button in milisecond:
var abc = setInterval(function () { var d = new Date(); var eta = 1527229800000 - d.getTime(); console.log(eta / 1000); if (eta < 0) { if (abc != null) clearInterval(abc); $("#Text").trigger("click"); } }, 1);
Zebra dialog box for jQuery mobile:
https://github.com/stefangabos/Zebra_Dialog
How to use region for coding in javascript:
//#region region name
Write your methods here.
//#endregion
To check in js mthod definition present or not:
if (typeof MethodName != "undefined" && jQuery.isFunction(MethodName))
Danger zone of coding in JavaScript:
1. We should not assign an array to another array because both will point to same location and changing one will affect directly to others.
Solution: jQuery.BinUtilizationDashboardNamespace.SelectedFilteredStorageType = jQuery.BinUtilizationDashboardNamespace.SelectedFilteredStorageType.concat(jQuery.BinUtilizationDashboardNamespace.SelectedStorageType);
2.Js variable not behaving properly due to same name as load parameter and global parameter
function BindBinUtilizationInfo(basicParam1, basePath, webServicePath, loadControlID) {
basicParam = basicParam1;
webServicePath = webServicePath;
loadControlID = loadControlID;
Note: Must never keep global and local variable as same name.
3.function will apply to div only when the div is loaded.
4. Ajax with xml return from webservice to javascript wont work with alone string as a return parameter we have to use the string in a object. And assign the html content to the string inside object and then return the object itself.
5. datepicker problem:
If we have datepicker but don't have date format assigned then on selecting date from from calendar wont be set the date in textbox.
How to prevent double click of server side button:
https://www.dotnetodyssey.com/2014/12/29/prevent-double-clicking-multiple-form-submission-asp-net-button-clicked/
<script type="text/javascript"> var isDone = false; function blockMultipleSubmissions() { if (!isDone) { $('#<%=btnSubmit.ClientID %>').val('Submitting.. Plz Wait..'); isDone = true; return true; } else { return false; }}</script><asp:TextBox ID="txtCounter" runat="server"></asp:TextBox><asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClientClick="return blockMultipleSubmissions();"
OnClick="btnSubmit_Click" />https://www.oreilly.com/library/view/knockoutjs/9781491914298/ch04.html
How to use if condition in aspx frontend using knockout:
<!-- ko if: IsGuru-->
<div class="teal bold tiny-leftmargin">
<%=GetGlobalResourceObject("Test", "testing")%>
</div>
<!-- /ko -->
/*Scan functionnality for label-Start*/
jQuery(document).on("pageinit", function () {
jQuery("#txtBOXID").scannerDetection({
timeBeforeScanTest: 200, // wait for the next character for upto 200ms
avgTimeByChar: 60, // it's not a barcode if a character takes longer than 100ms
endChar: [13],
minLength: 2,
onComplete: function (barcodeValue) {
jQuery("#txtBOXID").val(barcodeValue);
ScannerTimerForLabel();
}
});
});