[Javascript/Jquery/CSS] - A->Z
Saturday, March 14, 2020
JAVASCRIPT
Find element has <id> and change value itself.
Console / alert :
Object:
Number methods:
3. Getter/Setter in Javascript
Find element has <id> and change value itself.
document.getElementById("<id>").innerHTML = "Hello JavaScript";
document.getElementById("<id>").style.<attribute> = "<value>";Function:
function myFunction() { // return with object return object; } function myFunction() { // void function } function function1 (parameter1, parameter2, parameter3) { // code to be executed }Document:
document.write(<value>);
Console / alert :
// we console useful for debug a script. console.log(message); //alert show message to user but sometime we can use debug script.alert(message);
Object:
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; //access object person.firstName or person["firstName"];String method:
var str = "acb def abc"; str.length; // length no of String, value = 7 // returns the index of (the position of) the first occurrence of a specified textstr.indexOf("def"); //value = 4 //returns the index of the last occurrence of a specified textstr.lastIndexOf("abc"); // value = 8 // method searches a string for a specified value and returns the position of the match str.search("def"); // value = 4 //extracts a part of a string and returns the extracted part in a new string. str.slice(start_index, end_index);str.slice(7, 9); //value = abstr.slice(-9, -7); //value = ef // extracts a part of a string and returns the extracted part in a new (NOT ACCEPTED negetive index)str.substring(start_index, end_index);Ex: str.substring(7, 9); //value = ab // same slice but different second parameter is lengh of substring.str.substr(start, length); Ex: str.substr(7, 2); //value = ab str.replace(old string, new string); // Replace first search string str.replaceAll(old string, new string); // Replacea all search string
str.toUpperCase();
str.toLowerCase();
str.concat("string1","string2");
Number methods:
isNaN(x); // check is number or not. //returns a string, with the number written with a specified number of decimals var x = 1.876; x.toFixed(0); // returns 2 x.toFixed(2); // returns 1.88 //returns a string, with a number written with a specified length. x.toPrecision(); // returns 1.876 x.toPrecision(2); // returns 1.88 x.toPrecision(4); // returns 1.876 x.toPrecision(6); // returns 1.87600 Number() // Returns a number, converted from its argument. parseFloat() // Parses its argument and returns a floating point number parseInt() // Parses its argument and returns an integerCollection (Array, Map):
var array= ["a", "b", 10]; var temp; //accessarray[index]; //add element to arrayarray.push("Lemon"); for (i = 0; i < length of array; i++) { } //for each 1 array.forEach(myFunction); function myFunction(value) {...} //for each 2 array.forEach({ $(this) // element }); //push() var temp = ["a", "b"]; array.push(temp);
2. Detect select tab
<div id="tabDiv">
<ul>
<li><a href="#suspensionTab"><sm:msg code="Suspension_Activation_Replacement"/></a></li>
<li><a href="#terminationTab"><sm:msg code='Termination_Record_Master'/></a></li>
</ul>
<div id="suspensionTab">
<div id="terminationTab">
</div>
$('#tabDiv').click('tabsselect', function (event, ui) {
var activeTab = $('#tabDiv').tabs('option', 'active');
});
3. Getter/Setter in Javascript
Ref: https://stackoverflow.com/questions/49895080/javascript-class-getter-setter
class Form{
set foo(val){
console.log("setting foo")
this.fooValue = val;
}
get foo(){
console.log("getting foo");
return this.fooValue;
}
}
let frm = new Form();
frm.foo = "bar";
console.log(frm.foo);
var form = {
a: "aValue",
b: "bValue"
}
function withGetterSetter(obj){
var keys = Object.keys(obj);
var result = {};
for(var i=0;i<keys.length;i++){
var key = keys[i];
result[key+"_internal"] = obj[key];
(function(k){
Object.defineProperty(result,k, {
get:function() {
console.log("getting property:",k);
return this[k + "_internal"];
},
set: function(x) {
console.log("setting property:",k);
this[k + "_internal"] = x
}
});
})(key)
}
return result;
}
var setterObj = withGetterSetter(form);
console.log(setterObj.a);
setterObj.a = "updated";
console.log(setterObj.a);
4. Optional Chaining Operator
Directly use ?. inline to test for existence.
Ex: variable.properties1.properties2
if properties1 is null, the program will throw an undefined exception. Common, we usually check before used access.
if(variable.properties1 !== undefined && variable.properties1.properties2 !== undefined )
instead of we can use
variable.properties1?.properties2
Example:
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah',
},
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined
=========================================================================
ExtJs
Example code: https://hoquoctri.blogspot.com/2020/03/extjs-z.html
Lib: https://docs.sencha.com/extjs/4.2.0/#!/api/Ext
is updating...
=========================================================================
Regrex
Tool check: https://www.regextester.com/104043
1. Validate email
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;
2. Validate time
//hh:mm:ss
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;
ExtJs
Example code: https://hoquoctri.blogspot.com/2020/03/extjs-z.html
Lib: https://docs.sencha.com/extjs/4.2.0/#!/api/Ext
is updating...
=========================================================================
Regrex
Tool check: https://www.regextester.com/104043
1. Validate email
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;
2. Validate time
//hh:mm:ss
var regrex = /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/;
Ex:
console.log("isCorrectTime 23:59:59 " + isCorrectTime("23:59:59")); => true
console.log("isCorrectTime 23:59:59 " + isCorrectTime("23:59:59")); => true
console.log("isCorrectTime 09:36:55 " + isCorrectTime("09:36:55")); => true
console.log("isCorrectTime 24:59:59" + isCorrectTime("24:59:59")); =>f alse
3. Format Credit Card No:
Ex:
1111222233334444
=> 111122******4444
Regrex: /(?<=\d{6})(\d+?)(?=\d{4})/g
1111222233334444
=> 1111-2222-3333-4444
Regrex: /(\d{4})(?=\d)/gm
111122******4444
=>1111-22**-****-4444
Regrex: /\B(?=(\S{4})+(?!\S))/g
4. Mask by Jquery
Mask Transitions: The default available mask transitions are:
‘0’: {pattern: /\d/}
‘A’: {pattern: /[a-zA-Z0-9]/}
‘9’: {pattern: /\d/, optional: true}
‘S’: {pattern: /[a-zA-Z]/}
‘#’: {pattern: /\d/, recursive: true}
The value must match the digit of the pattern.
In this example: Credit card = 16 digit correctponding 16 of "0".
$(".selector").mask('0000-0000-0000-0000-0000');
Mask Credit Card: 1111222233334444 => 1111-2222-3333-4444
4. Remove HTML tab
const regex = /<(?:.|\n)*?>/gm;
const result = htmlContent.replace(regex, '');
5. Encode URL
If your URL has a special character such as #, ? ,... you should encode your url and decode in another side.
let uri = "car=sa#ab###";
let encoded = encodeURIComponent(uri);
let decoded = decodeURIComponent(encoded);
6. Array includes()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // return true if existed
7. Jquery: Disable/Enable Select Box in HTML
$('#verifiedYN').removeAttr('disabled');
$('#actionType').attr('disabled', 'disabled');
// Get text from Select Box
$('#id').find(":selected").text();
//Get value from Select Box
$('#id').find(":selected").val();
#Check/Unchecked
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
#Select in SelectBox
$("#MySelectBox").val("5");
7. Get/Set value from <span>
$("#submittername").text("testing"); //get & set
$("#submittername").html("testing <b>1 2 3</b>");
8. Set img src
$("#my_image").attr("src","second.jpg");
is updating...
Bài liên quan
Comments[ 0 ]
Post a Comment