lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I am trying to push a new row of data to a table , after submitting the form . However , the table , which is called UrlListCtrl is different from the form , which is UrlFormCtrl.In UrlFormCtrl , I am sending an array to the database to be stored , afterwards I 'd like to update the view , where UrlListCtrl handles it....
function UrlFormCtrl ( $ scope , $ timeout , UrlService ) { $ scope.message = `` ; var token = `` ; $ scope.submitUrl = function ( formUrls ) { console.log ( 'Submitting url ' , formUrls ) ; if ( formUrls ! == undefined ) { UrlService.addUrl ( formUrls ) .then ( function ( response ) { $ scope.message = 'Created ! ' ; ...
Update model from inside of another controller
JS
I am creating a form with React , and have created a < Field / > component that needs to render different wrapper elements based on the number of children of a specific type.For instance , if the field wraps a single input , it should render a wrapper < div / > and a < label / > . However if it wraps multiple inputs , ...
const FormFieldContext = createContext ( { } ) ; // Simplified Field componentconst Field = ( { label , children , ... props } ) = > { const [ fieldCount , setFieldCount ] = useState ( 0 ) ; const Wrapper = fieldCount > 1 ? 'fieldset ' : 'div ' ; const Label = fieldCount > 1 ? 'legend ' : 'label ' ; return ( < Wrapper ...
Is setting parent state on child mount an anti-pattern ?
JS
This one does n't work , because of date==date1 . If I change it to date < =date1 , it works fine . I thought javascript is a weakly typed language and it compares the content , rather than reference . I do n't wan na do something like ( date.getDay==date1.getDay & & ... . ) . Is there an easier way to compare the valu...
.Highlighted a { background-color : Green ! important ; background-image : none ! important ; color : White ! important ; font-weight : bold ! important ; font-size : 9pt ; } $ ( document ) .ready ( function ( ) { var date1 = new Date ( 2014 , 5 , 6 ) ; var date2 = new Date ( 2014 , 5 , 17 ) ; $ ( ' # datepicker ' ) .d...
Why does datepicker highlight not work when I use `` == '' ?
JS
This piece of CoffeeScript : is compiled to : I do n't understand why it does n't just use an i . Any ideas ?
for i in [ 1..10 ] console.log i for ( i = _i = 1 ; _i < = 10 ; i = ++_i ) { console.log ( i ) ; }
Why does CoffeeScript compile a for loop in this way ?
JS
I need a regex for javascript that allows me to select a single character with a restriction : that it does NOT have a specified character besides itself.I need to select the character /but only if it does NOT have the character a besides it.E.g . : And the result should be something like this : The regex should be som...
str = `` I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t '' ; myregex = ? ? ? ? var patt = new RegExp ( myregex ) ; var res = patt.split ( str ) ; res [ 0 ] = `` I Like this '' res [ 1 ] = `` and a/ basketball is round a/a ups.Papa/ tol '' res [ 2 ] = `` d `` res [ 3 ] = `` me tha/t ''
How to make a regex for capturing one symbol only , but with restrictions ?
JS
Let b = 2 ( without a semicolon ) will give an error:2.Let c = 3 without a semicolon , no error , c will turn into an array . Why is this ?
let a = 1let b = 2 [ a , b ] = [ b , a ] console.log ( a ) console.log ( b ) let a = 1let b = 2let c = 3 [ a , b ] = [ b , a ] console.log ( a ) console.log ( b ) console.log ( c )
Ask everyone a question , how is this analyzed ?
JS
I have a simple app that outputs messages when some actions are performed on a page , and it is done through the javascript createElement function , what I want to do is add a special style to only the newest message , so if a newer messages comes up the old newest message would revert to the old style . Is there any w...
function selfMsg ( message ) { const msg = document.createElement ( 'div ' ) ; msg.style.cssText = 'display : flex ; justify-content : flex-end ; background-color : aquamarine ' ; msg.innerText = message ; display.append ( msg ) ; }
Styling only the newest line of output in div
JS
I 've got a form with a submit button , and I want to show a dialog before continuing the form submission . The code below is showing the dialog properly , but it continues the submit anyway :
@ using ( Html.BeginForm ( `` SubmitForm '' , `` Home '' , FormMethod.Post , new { id = `` form '' } ) ) { @ Html.AntiForgeryToken ( ) *snip* < div class= '' collapseClosed panel-footer panel-collapse collapse in '' > < input type= '' submit '' name= '' btnSubmit '' id= '' btnSubmit '' class= '' btn btn-success '' valu...
How can I show a dialog before submitting ?
JS
I have three different array of objects that I need to sort over a Date field , where the field has a different name in each group . Below an example of my data : GOAL : return the lastest 4 results ( this I can get with a .reverse ( ) once I have a final set listed ASC ) , independently from which source they come fro...
const documents = [ { documentId : 'ADB0125A ' , fileName : 'test_2018.pdf ' , date ' : '2017-12-02T19:08:52+01:00 ' // Field to sort by } , { documentId : '123456 ' , fileName : 'test2_2018.pdf ' , date ' : '2017-12-12T22:08:52+01:00 ' // Field to sort by } , { documentId : '121212 ' , fileName : 'test3_2018.pdf ' , d...
Sort three distinct arrays of objects by property
JS
I need to do some split , like this : But those /* characters , make my code be as a comment.How can I use it & avoid from this to happen ?
$ ( element ) .split ( /* ( .+ ) ? / ) [ 1 ] ) ;
Regex - Use /* in JS without getting my code in comment
JS
I am trying to create the following array by using for loop . However , my result is an array with the length of 24 and all objects inside become { key : '23 ' , text : '12:30 ' , value : '12:30 ' } , rather than iterating one by one . Can anyone explain to me why each iteration would override the previous one ? This i...
const timeOptions = [ { key : ' 0 ' , text : ' 1:00 ' , value : ' 1:00 ' } , { key : ' 1 ' , text : ' 1:30 ' , value : ' 1:30 ' } , { key : ' 2 ' , text : ' 2:00 ' , value : ' 2:00 ' } , { key : ' 3 ' , text : ' 2:30 ' , value : ' 2:30 ' } , { key : ' 4 ' , text : ' 3:00 ' , value : ' 3:00 ' } , { key : ' 5 ' , text : ...
Setting up object key-value pairs via array iteration
JS
I was just looking through Mozilla Developer documentation , and found notation that I do n't know what is used for and also can not find any information through internet.Array filter polyfill - line 10Any suggestions what this operator is for ?
var t = Object ( this ) ; var len = t.length > > > 0 ;
`` > > > '' operator - what is used for ?
JS
I have 2 .school , several .class-room and there are some .my-child inside.If .my-child is located in the first .class-room of a school , I want to style that school with yellow background . But it does n't show as expected.jsfiddle
$ ( '.school ' ) .each ( function ( ) { $ ( this ) .find ( '.my-child ' ) .each ( function ( i , el ) { $ ( this ) .addClass ( 'child ' + ( i + 1 ) ) ; } ) ; if ( $ ( '.school .class-room : first-child ' ) .children ( ) .hasClass ( '.my-child ' ) ) { $ ( '.school ' ) .css ( 'background ' , 'yellow ' ) ; } } ) .my-child...
How to style elements if first-child hasClass ?
JS
Is there a way to replace the last item in array with one line of code ? What I receive : What I want : Code so far : Error : Update : Nina answered it . I also had a case where I need to insert a value at the end of the string ( add in a name to a file path ) . It 's the same as above but replaces everything right bef...
return `` my.long.string '' ; return `` my.long.output '' ; var value = `` my.long.string '' ; var newValue = value.split ( `` . '' ) .pop ( ) .join ( `` . '' ) + `` output '' ; SyntaxError : Unexpected string var value = `` my.long.string '' ; var result = value.split ( `` . `` ) .slice ( 0 , -1 ) .join ( `` . '' ) + ...
Replace a value at the end of a string converted to an array in one line ?
JS
I think I am doing the same for two different elements ( # tu , # chr_1 ) but they behave differently for some reason I can not figure out.I want the feedback element to be in the same location as the dragged window and the target so that I can give some feedback in-place.Interestingly , the # chr_1 properly aligns in ...
.draggable { font-size : 2em ; text-align : center ; vertical-align : middle ; width : 30px ; height : 30px ; padding : 0em ; float : left ; margin : 0em ; background-color : orange ; z-index : 10 ; visibility : visible ; } .droppable { font-size : 2em ; text-align : center ; vertical-align : middle ; width : 30px ; he...
Element not showing up in expected location ( x )
JS
I have the following function defined in my site . It works for some people , not for others . The exception occurs on the last line in the method , where the concatenation is . I believe that because url 's question mark character designating the query string is being looked as a ternary operator.Is there something he...
function popUp ( url ) { var myleft = ( screen.width ) ? ( screen.width - 750 ) / 2 : 100 ; var mytop = ( screen.height ) ? ( screen.height - 300 ) / 2 : 100 ; var id = new Date ( ) .getTime ( ) ; eval ( `` page '' + id + `` = window.open ( `` + url + `` , ' '' + id + `` ' , 'toolbar=0 , scrollbars=0 , location=0 , sta...
Unknown reason for `` Expected ' : ' '' error in javascript
JS
How to get objects with the same property and has the max value in array I have a data likeAnd I want the resultIs there any better ways than what I did here ?
data = [ { title : `` test1 '' , version : 1 } , { title : `` test2 '' , version : 3 } , { title : `` test1 '' , version : 2 } , { title : `` test2 '' , version : 2 } , { title : `` test2 '' , version : 1 } ] ; result = [ { title : `` test1 '' , version : 2 } , { title : `` test2 '' , version : 3 } ] ; var titles = [ ....
how to get objects with the same property and has the max value in array - Javascript
JS
I encountered the code like below.I do not understand the two expressions in the code : This looks like IIFE ( Immediately invoked function expression ) , however , I do not understand how the brackets at the end of the line exactly work or what they are doing.Could anyone help me understand this ?
return new Promise ( function ( resolve , reject ) { if ( ! message ) return reject ( new Error ( 'Requires message request to send ' ) ) ; message = ( 0 , _getURLJWT ) ( message ) ; ... .. ... .. var enc = ( 0 , _encryptMessage ) ( plaintext , pubEncKey ) ; } , function ( error , res , body ) { ... . ... . } ) ; } ) ;...
What does var name = ( ) ( ) do ?
JS
I want to replace some of the words from the user 's input using customized characters . The string will be like thisThis is what I tried to do But it is not working . I want something like this : Any idea ?
var userInput = `` five plus five equal to ten multiply 5 '' ; const punctLists = { name : 'star ' , tag : '* ' } , { name : 'bracket ' , tag : ' ) ' } , { name : 'multiply ' , tag : '* ' } , { name : 'plus ' , tag : '+ ' } , { name : 'double equals ' , tag : '== ' } , { name : 'equal ' , tag : '= ' } ] var matchPuncti...
Replace multiple occurance in string
JS
I have a table and i am adding new row through javascript and adding an event on new row as well but it 's not working.Here is my code : getstock is working for the first row but not for other rows and when i inspect the select dropdown it shows below :
function moreitem ( ) { document.getElementById ( 'tottr ' ) .value = parseInt ( document.getElementById ( 'tottr ' ) .value ) + 1 ; ain = document.getElementById ( 'tottr ' ) .value ; $ ( ' # mytable tbody tr : last ' ) .after ( `` < tr > < td > < select name='pid [ ] ' id= '' class='form-control ' onchange='getstock ...
Adding variable value on onchange event
JS
I 'm trying to animate the background of my website , which has a solid background , and then I want to `` sketch '' gridlines over it . Right now I have the background drawn as such : I want it to be like this , except I want the linear-gradients to load one-by-one and make them look sketched in if possible.I tried lo...
background-color : # 269 ; background-image : linear-gradient ( @ light-grey 2px , transparent 2px ) , linear-gradient ( 90deg , @ light-grey 2px , transparent 2px ) , linear-gradient ( rgba ( 255 , 255 , 255 , .3 ) 1px , transparent 1px ) , linear-gradient ( 90deg , rgba ( 255 , 255 , 255 , .3 ) 1px , transparent 1px ...
How can I draw in gridlines in the background of a website after loading ?
JS
BackgroundConsider the following custom input ( ignore the JS ) : I apologise for the quantity of CSS , I tried to strip out as much as possible but needed the functionality to be there in order to demonstrate the issue ... The ProblemForgive me for being somewhat of a perfectionist , but I have noticed a very slight i...
$ ( document ) .ready ( ( ) = > { $ ( 'input ' ) .focus ( function ( ) { $ ( this ) .closest ( '.field-container ' ) .addClass ( 'focused ' ) ; } ) ; $ ( 'input ' ) .blur ( function ( ) { $ ( this ) .closest ( '.field-container ' ) .removeClass ( 'focused ' ) ; } ) ; } ) ; html , body { background : # eee ; } .field-co...
z-index issue with custom form field ( select )
JS
Given the following arrays : Using node v 7.3.0 I observe the following unexpected behavior : Sample Snippet : However code like x.find ( element = > y.includes ( element ) ) ; always finds the element as expected.I do n't get why the two calls that just use find and includes would ever yield different results and woul...
const x = [ 2 , 14 , 54 , 109 , 129 , 136 , 165 , 312 , 320 , 330 , 335 , 348 , 399 , 440 , 450 , 461 , 482 , 501 , 546 , 547 , 549 , 559 , 582 , 584 , 615 , 620 , 647 , 682 ] ; const y = [ 539 , 681 , 682 , 683 ] ; [ > x.find ( y.includes , y ) ; undefined [ > y.find ( x.includes , x ) ; 682 const x = [ 2 , 14 , 54 , ...
Array confusion with find and includes
JS
I have the following ( simplified ) markup code : I want to take advantage of bubbling by attaching an event listener only on the # container , and get the clicked children 's data-value.Everything works fine if the clicked area is the div area ( in red in the fiddle ) . How can I get the data-value also when the click...
< div id= '' container '' > < div data-value= '' 1 '' > < span > Click me 1 < /span > < /div > < div data-value= '' 2 '' > < span > Click me 2 < /span > < /div > < /div > < div id= '' messages '' > < /div > document.getElementById ( 'container ' ) .addEventListener ( 'click ' , function ( e ) { document.getElementById ...
JavaScript events and bubbling
JS
Following is a deeply nested object with properties recurring.How to convert the following deeply nested object into this :
const obj = { prop1 : { properties : { value : { } } , } , prop2 : { properties : { subProp : { properties : { value : { } } } } , } , prop3 : { properties : { subProp : { properties : { subSubProp : { properties : { value : { } } } } } } , } , } ; const obj = { prop1 : { value : { } } , prop2 : { subProp : { value : {...
How to convert object deep properties in to another ?
JS
I 'm trying to figure out how to sum accumulatives values over time of two arrays , seems simple , but here 's what complicates it : there might be missing dates from one of them.When one has a value for a date and the other does n't , we sum together that value that exists from one array and the last-seen ( previous )...
var data1 = [ { date : `` 30-08-2019 '' , value : 1 } , { date : `` 03-09-2019 '' , value : 2 } , { date : `` 04-09-2019 '' , value : 3 } ] var data2 = [ { date : `` 30-08-2019 '' , value : 1 } , { date : `` 02-09-2019 '' , value : 2 } , { date : `` 03-09-2019 '' , value : 3 } , { date : `` 04-09-2019 '' , value : 4 } ...
Summing two ordered arrays of accumulative object values over time
JS
ANSWERED by FissioI am trying to make a simple search feature in Angular . When the user types in something in the input field , I want to search through all the 'titles ' in my JSON , and if a word matches with the input , then I want to bring back all the objects related to the match.FACTORYI first created a Factory ...
.factory ( 'podcastData ' , function ( $ http ) { var podcastData = { async : function ( ) { var promise = $ http.get ( 'http : //radio-sante-animale.fr/podcast-data.php ' ) .then ( function ( response ) { return response.data.categories ; } ) return promise ; } } ; return podcastData ; } ) $ scope.findValue = function...
How to get Object Index by Value ?
JS
I will show you a little part of my app where I am wondering which is the proper way to put a conditional I am working on . If both ways I will show you are correct , I would like you to tell me the consequences/adversitiesthat is how I have it so far , is there something bad with it ? or should be better this way : so...
if ( ( some.thing === `` || 0 ) || ( some.how === `` || 0 ) ) { //something is going on here } if ( ( some.thing === `` || some.thing === 0 ) || ( some.how === `` || some.how === 0 ) ) { //something is going on here } if ( some.thing === `` || some.thing === 0 || some.how === `` || some.how === 0 ) { //something is goi...
Getting clear with special conditional statement
JS
I have this navigation bar with position : sticky , but it stops when it reaches the top of the side navigation and the content of the page . I ca n't change the position tofixed , because then the .ad above it wo n't be visible . I have added the scripts that belong to the side navigation and the content.How do I make...
function sortBooks ( upDown ) { var columns = document.getElementsByClassName ( `` column '' ) function pricesToArray ( columns ) { var prices = [ ] ; for ( var index = 0 ; index < columns.length ; index++ ) { var price = columns [ index ] .querySelector ( '.price ' ) .innerText ; var priceInt = price.substr ( 1 , pric...
Sticky navigation bar stops working due to content underneath
JS
I ’ m trying to make a wrapper component for ngAudio the wrapper itself would be the player with controls - and would interact with ngAudio ’ s functions . I ’ m having some scope issues with it , I can inject it into the component ’ s controller and access ngAudio there , but I can not access it from the scope of the ...
.component ( 'player ' , { // isolated scope binding bindings : { genre : '= ' , track : '= ' , ngAudio : ' < ' } , templateUrl : '/templates/player-directive-template.html ' , // The controller that handles our component logic controller : function ( $ scope , ngAudio ) { //tried : // $ scope.ngAudio = ngAudio ; ngAud...
Can not access module from directive template , Angular
JS
I 'm using webpack with css-loader . Everything has been working fine except that I do n't know how to use jQuery to select a css-loader transformed class . The transformed class name looks something like this `` src-styleauthTextboxLeft1Npf4 '' with the following css-loader configuration : Here 's the React codeIs the...
css ? sourceMap & modules & importLoaders=1 & localIdentName= [ path ] [ name ] __ [ local ] __ [ hash : base64:5 ] ' const Auth = ( props ) = > { const toggle = ( event ) = > { // Working example $ ( ' # container ' ) .css ( 'background ' , 'blue ' ) ; // Not working $ ( styleCSS.container ) .css ( 'background ' , 'gr...
How to use jQuery to select a class name that 's transformed by css-loader ?
JS
After writing the following code the color stops at the end of the line and starts again at the next line . I want it to continue and end with a different color till it reaches the end of second line . Then continue doing so.Here is my css class that I am using on a p tag.Here is what I am getting : And here is what I ...
$ font : 'Poppins ' , sans-serif ; .text { background : linear-gradient ( to right , # 000000 0 % , # 4ad7fa 100 % ) ; -webkit-background-clip : text ; -webkit-text-fill-color : transparent ; font : { size : 3vw ; family : $ font ; } ; }
How can I color text with a gradient color which adapts with the screen size and continues the color on the new line ?
JS
I want to send an array of objects with other forms of data to MVC action using ajax.and some other form fields data.I tried getting and attaching form data like this : But in the server-side , I get an array of 5 elements with null values in Features property.here is my server-side code . my object : and my action : T...
var arr = [ { Name : `` a '' , IsActive : `` true '' } , { Name : `` b '' , IsActive : `` false '' } , { Name : `` c '' , IsActive : `` true '' } , { Name : `` d '' , IsActive : `` false '' } , { Name : `` e '' , IsActive : `` true '' } ] ; $ ( document.body ) .delegate ( `` form # mainFormCreate '' , `` submit '' , fu...
How to send an array of objects along with other formdatas using ajax ?
JS
Is there a way to know what dependencies were injected into my Angular module ?
angular.module ( 'myModule ' , [ 'ui.bootstrap ' ] ) .controller ( 'myController ' , [ function ( ) { // var dependencies = Magic.dependencies ; // console.log ( dependencies ) ; } ] ) ;
List dependencies injected
JS
I have the following output numbers from prices of products : I want to round them up always no matter what price is , so the result in this case would be : I tried with this code but it just removes the whole number : Any idea where is the problem ?
< span class= '' amount '' > 77.08 < /span > < span class= '' amount '' > 18.18 < /span > < span class= '' amount '' > 20.25 < /span > < span class= '' amount '' > 78 < /span > < span class= '' amount '' > 19 < /span > < span class= '' amount '' > 21 < /span > jQuery ( '.amount ' ) .each ( function ( ) { jQuery ( this ...
Round up number with decimals
JS
I need to highlight a block of code but at the same time , I need the code to be placed on separate and numbered lines , to leave comments for each line of code , just as can be done on Github . I managed to do this but because I highlight the code for each line , the `` SQL '' code that is on several lines will not be...
if ( data.success === 1 ) { setCodeLanguage ( translateLanguage ( data.code.language ) ) ; let rows = [ ] ; data.code.source_code.split ( `` \n '' ) .forEach ( ( line , index ) = > { rows.push ( < tr key= { index } className= '' line '' > < td className= '' line-number '' > { index + 1 } < /td > < td id= { `` plus '' +...
How can I correctly highlight a line by line code , using highlight.js ( React ) ?
JS
Can somebody explain the behaviour of the following code ? Why is it that even an array can be used to access a property inside an object ? As a side note this only works with an array of length 1 . I have tried researching this but there 's no documentation as far as I know that explains why this should work .
let obj = { a:1 , b:2 } let i = [ ' a ' ] console.log ( obj [ i ] ) > > 1
Why can I access object property with an array ?
JS
I 'm trying to retrieve the calculation of the text within < li > but I do n't need the child tag < p > to be considered in this calculation.So when I add the following it will naturally calculate all the text within < li > .From HTML : What are the possible ways to achieve this so the child tags text is not calculated...
$ ( 'ul li ' ) .text ( ) .length ; < ul > < li > Count me < p > Do n't count me please. < /p > < /li > < /ul >
Retrieve text from list tag but do n't calculate the child tag
JS
What is the difference between the following two JavaScript functions ? I know variables declared with var are local inside the function , and if declared withthis ` keyword are exposed to outer word . is there any other difference between and
function student ( param1 , param2 , param3 ) { this.name = param1 ; this.age = param2 ; this.address = param3 ; } function student ( param1 , param2 , param3 ) { var name = param1 ; var age = param2 ; var address = param3 ; }
Trying to understand scoping within two short JavaScript functions
JS
To all string manipulation maestros , this might be an interesting exercise . Given a string containing `` x '' or `` xx '' scattered in quasi-random places ( like a DNA sequence ) , I need to permutate this string by varying the `` x '' in it . Each instance of `` x '' can be a singular `` x '' or a double `` xx '' , ...
[ `` ooxxooxoo '' , `` ooxooxxoo '' , `` ooxxooxxoo '' ] [ `` ooxooxoo '' , `` ooxooxxoo '' , `` ooxxooxxoo '' ] [ `` ooxxooxoox '' , `` ooxooxxoox '' , `` ooxooxooxx '' , `` ooxxooxxoox '' , `` ooxxooxooxx '' , `` ooxooxxooxx '' , `` ooxxooxxooxx '' ] function heapsPermute ( aInput , aOutput , n ) { var swap = functio...
How to permutate a string by varying one character in JavaScript ?
JS
I feel like there 's probably something incredibly simple I missed in the MDN docs or something , but I 've been digging for a while , and I have no clue.Is there a way to call a function in a similar way to a method ? This is basically what I 'm trying to do : Now , mind you , I 'm not trying to make a constructor or ...
function addItem ( itemName , quality , quantity /* , arr*/ ) { arr.push ( [ itemName , quality , quantity ] ) ; } var someArr = [ [ 'item ' , 1 , 1 ] ] ; someArr.addItem ( 'someOtherItem ' , 2 , 3 ) ; // someArr === [ [ 'item ' , 1 , 1 ] , [ 'someOtherItem ' , 2 , 3 ] ]
Add function as method of Array native object ( Is it possible to call a function as a method ? )
JS
In the following input string : I am trying to match all instances of { $ SOMETHING_HERE } that are not preceded by an unescaped backslash.Example : I want it to match { $ SOMETHING } but not \ { $ SOMETHING } . But I do want it to match \\ { $ SOMETHING } Attempts : All of my attempts so far will match what I want exc...
{ $ foo } foo bar \\ { $ blah1 } oh { $ blah2 } even more { $ blah3 } but not { $ blarg } { $ why_not_me } var input = ' { $ foo } foo bar \\ { $ blah1 } oh { $ blah2 } even more { $ blah3 } but not { $ blarg } { $ why_not_me } ' ; var results = input.match ( / ( ? : [ ^\\ ] |^ ) \ { \ $ [ a-zA-Z_ ] [ a-zA-Z0-9_ ] *\ }...
Regular Expression Guidance needed for Javascript
JS
I am creating a sample MabLibs type thing in HTML and JS . When the person inputs stuff in a field , it will use that to create their own MadLib.I 've done a little research and not finding exactly what I am looking for . Say a person puts 12 in the Name field . How would code that so if this instance does happen , it ...
< html > < head > < title > Mad Libs Story < /title > < script > function getVars ( ) { person1 = String ( document.getElementById ( `` personOne '' ) .value ) ; age = Number ( document.getElementById ( `` ageOne '' ) .value ) ; firstAdjective = String ( document.getElementById ( `` adjective '' ) .value ) ; document.g...
Prevent Wrong Input in JS After Submitting A Form
JS
Is there anyway that we can deal with falsy values in || operators that are lazily evaluated ? So , for example if we have : In ES6 , you can simply declare it likeIs there anythning we can do in ES5 to avoid this issue ?
function isOldEnough ( age ) { age = age || 18 ; return age ; } isOldEnough ( 0 ) // returns 18 because 0 is falsy function isOldEnough ( age = 18 ) { ... }
Avoiding Pitfalls with Assigning Falsy Values in Defaults ?
JS
I am trying to center these boxes in the middle of the screen both horizontally and vertically . Another question is how can I make it where it re-sizes automatically when I scale my page ?
/* -- -- -- -- -- -- -- -- -- -- -- -- - Simple reset -- -- -- -- -- -- -- -- -- -- -- -- -- */* { margin:0 ; padding:0 ; } /* -- -- -- -- -- -- -- -- -- -- -- -- - General Styles -- -- -- -- -- -- -- -- -- -- -- -- -- *//* -- -- -- -- -- -- -- -- -- -- -- -- -- -- Color Themes -- -- -- -- -- -- -- -- -- -- -- -- -- --...
Centering CSS Boxes ( Html and Css )
JS
I just experienced the strangest thing , this is the code I 'm actually using : As you would expect , the log should give the number of each row ( 0 , 1 , 2 ... ) , instead it gives me this : Knowing that my array only has 3 rowsDid anybody ever encountred this ?
for ( iter in data.List ) { console.log ( iter ) ; } 012remove
For loop in array reads 'remove ' ?
JS
Here is the scripts : http : //jsbin.com/itusut/6/editHi , i have function : if we do var handle = document.getElementsByClassName ( 'some-class ' ) ; then handle is a node list.if we do var handle = document.getElementById ( 'an-id ' ) ; then handle is a single node.The problem is , when i choose < form id= '' login-f...
function on ( t , e , f ) { if ( e.length ) { var l = e.length , n = 0 ; for ( ; n < l ; n++ ) { e [ n ] .addEventListener ( t , f , false ) } } else { e.addEventListener ( t , f , false ) ; } }
javascript : how to distinguish between selected element list and form
JS
Currently , Sails serves the images hosted in assets/images folder , however , I need a different approach because the images will be hosted in a CDN system ( AWS Cloudfront ) , so the images ' URLs follow a structure like this : Therefore , How can I approach this ? , How can I approach this in order to Sails automati...
https : //hdfhhfh.cloudtfront.net/images/image.jpg
How can I generate the external url for images in Sails ?
JS
In Javascript , almost all expressions ( all expressions ? ) have a `` truthiness '' value . If you put an expression in a statement that expects a boolean , it will evaluate to a boolean equivalent . For example : In some workplaces it is common to coerce an expression in this situation into an actual boolean by negat...
let a = 'foo'if ( a ) { console.log ( ' a is truthy ! ' ) ; } // Will print ' a is truthy ! ' . let a = 'foo'if ( ! ! a ) { console.log ( ' a is truthy ! ' ) ; } // Will print ' a is truthy ! ' .
Are there any Typescript expressions ` A ` such that the truthiness of ` A ` is different from ` ! ! A ` ?
JS
I am still new to JavaScript . I need to create a button in html and allow the user to click the button to change the specify body background color . Above is the given array in the JavaScript . If the user click more than 3 times ( after blue color ) , the green color will be selected again.I roughly write the functio...
var colors = [ `` purple '' , `` yellow '' , `` black '' ] ; < form > < p > < input type= '' button '' value= '' Change Color '' name= '' B1 '' onclick= '' changeColor ( ) '' > < /p > < /form > function changeColor ( ) { document.body.style.backgroundColor= '' colors [ i ] '' ; i++ if ( i > =2 ) { i = 0 ; } }
HTML Javascript about array .
JS
Given the following HTML structure : the following is false : even though : Could anyone explain why ? Thanks !
< div class= '' wrap '' > < div id= '' a '' > < /div > < div id= '' b '' > < /div > < /div > ( $ ( ' # a ' ) .parent ( ) == $ ( ' # b ' ) .parent ( ) ) ; //= > false $ ( ' # a ' ) .parent ( ) .children ( ' # b ' ) .length ; //= > 1
Ensure two items are siblings in JS / jQuery
JS
Everybody knows the basic concatenation of two strings in JavaScript : But what happens if we use + + instead of + ? I just encountered the following weird behavior : From the examples above , I can see that the second string is converted into number . So , passing an object having valueOf property as function , the va...
> `` Hello `` + `` World ! `` 'Hello World ! ' > `` Hello `` + + `` World ! `` 'Hello NaN ' > `` Hello `` + + `` '' 'Hello 0 ' > `` Hello `` + + ( { valueOf : function ( ) { return 1 ; } } ) 'Hello 1 '
Weird behavior when using + + in JavaScript
JS
I am toying around with JavaScript generators and have 2 questions based on the following code and its output : Question 1It seems like every generator object has its own unique prototype , and they all share a common prototype : Is my above understanding correct ? Question 2Since f is null , e is probably Object.proto...
const a = function* ( ) { } ( ) ; // Object [ Generator ] { } const b = a.__proto__ ; // Object [ Generator ] { } const c = b.__proto__ ; // Object [ Generator ] { } const d = c.__proto__ ; // { } const e = d.__proto__ ; // { } const f = e.__proto__ ; // nullconsole.log ( a , b , c , d , e , f ) ; const x = function* (...
JavaScript generators and their prototype chains
JS
Sometimes in the internet I see a syntax that is strange to me . Something like : How does this `` equal '' sequence work ? Thanks .
console.log = console.error = console.info = console.debug = console.warn = console.trace = function ( ) { }
Javascript `` Equal Sequence '' meaning
JS
Here is the exampleThe question is - why getResult function calls immediately ? children component in Wrapper should be rendered after 3s . But function calls immediately anyway . Why is so ?
const getResult = ( ) = > { document.getElementById ( 'logger ' ) .innerHTML += `` FUNCTION CALLs immediately '' ; return 'RESULT string AFTER 3S ' ; } const A = ( ) = > { return ( < Wrapper > { getResult ( ) } < /Wrapper > ) ; } ; class Wrapper extends React.Component { constructor ( ) { super ( ) ; this.state = { act...
Why react calls function in subcomponents event when this subsomponents not rendered ?
JS
I 'm trying to track a chrome extension on Google Analytics.It looks like it 's configured correctly but I ca n't see the data on the dashboard . Not sure if it 's a delay , if it 's being ignored because I 'm running the extension on development mode or if I need to configure something else.I 'm using the following co...
const gaScript = document.createElement ( 'script ' ) ; gaScript.type = 'text/javascript ' ; gaScript.async = true ; gaScript.src = 'https : //ssl.google-analytics.com/analytics.js ' ; gaScript.onload = function ( ) { ga.l = +new Date ; ga ( 'create ' , 'MY_CODE ' , 'auto ' ) ; ga ( 'set ' , 'checkProtocolTask ' , null...
How to check if my google analytics is working on a chrome extension ?
JS
I need to reduce the given object into some datastructure . This is my input object.Desired output : I have tried doing but i was getting some problems . I am getting some duplicate properties which should be there . I can share the code on what i have tried.Actual result which i got : Is there any optimal way of doing...
const receiver = { USER1 : { module : [ 'a_critical ' , 'a_normal ' , 'b_normal ' ] } , USER2 : { module : [ 'a_critical ' , 'a_normal ' , 'b_critical ' ] } , USER3 : { module : [ 'a_critical ' ] } } ; const allModules = [ 'a_normal ' , 'a_critical ' , 'b_normal ' , 'b_critical ' ] ; { `` a_critical '' : [ { `` user ''...
Javascript - reduce the given object into one data structure
JS
I need to make a wrapper function to invoke a function multiply with a given number num of times to allow the multiply to execute . nTimes ( num,2 ) Then assign to runTwice -- runTwice can be any function that invoke the nTimes function which given a different num input -- In my case , for simplicity , I am only allowi...
'use strict'//use a counter object to keep track of counts , max number allowed to run and latest result renderedlet counter = { count:0 , max : 0 , lastResult : 0 } ; let multiply = function ( a , b ) { if ( this.count < this.max ) { this.count++ ; this.lastResult = a*b ; return a*b ; } else { return this.lastResult ;...
Only allowing a function to run n times with wrapper function
JS
I have a file input : I have a preview img : I want to set the image as a file for the file-input # myImageInput.What I try : Create Base64 from the img # myImagePreview : Create DataTransfer and add the base64Image to it : Console.log the # myImageInput.files : This does n't look right but it actually set a `` file ''...
< input type= '' file '' id= '' myImageInput '' accept= '' image/* '' > < img src= '' http : //myImageUrl '' id= '' myImagePreview '' > function toDataUrl ( url , callback ) { var xhr = new XMLHttpRequest ( ) ; xhr.onload = function ( ) { var reader = new FileReader ( ) ; reader.onloadend = function ( ) { callback ( re...
Set file-input file from url
JS
Imagine a React page that allows users to edit a bill ( invoice ) . The bill has a fair number of editable fields , say 100 . Additionally , a bill can have any number of line items . Let 's imagine 100 of them , each with , say , 20 fields.If the bill is the `` parent , '' and is rendered by a React component , the li...
const INITIAL_STATE = { invoiceNumber : `` ABC123 '' , customer : `` Phil 's Dills '' , lineItems : [ { index : 0 , item : `` Pickles '' , quantity : 2 } , { index : 1 , item : `` Pickle Juice '' , quantity : 5 } , ] } export function Bill ( ) { const [ bill , setBill ] = useState ( INITIAL_STATE ) ; function updateBil...
React : how to maintain performance when updating a large parent record from a controlled child input field ?
JS
I have an array [ 1 , 2 , 3 ] and I want to transfer it to object with nested parent-child objects 's series like this : If I have an array [ 1 , 2 , 3 , 4 ] the result will be like this : The best effort of me is this snippet of code :
{ value : 1 , rest : { value : 2 , rest : { value : 3 , rest : null } } { value : 1 , rest : { value : 2 , rest : { value : 3 , rest : { value:4 , rest : null } } const arrayToList = ( array ) = > { let list = { value : null , rest : null } ; for ( let e of array ) { array.indexOf ( e ) === 0 & & ( list.value = e ) ; a...
How to create Object with nested Objects from an Array
JS
Background explanationI have asked a question concerning defining an date array using a loop . The array is defined on basis of a declared variable named `` dateinterval '' . The way I designed the code resulted in an error message in relation to another loop and another user provided another loop for me which solved t...
for ( var i=0 ; i < difference ; i++ ) { dateinterval [ dateinterval.length ] = dateinterval [ 0 ] .setDate ( datointerval [ 0 ] .getDate ( ) + i ) ; } ; for ( var i = 0 ; i < difference ; i++ ) { var dt = new Date ( dateinterval [ 0 ] ) ; dt.setDate ( dt.getDate ( ) + i ) ; dateinterval [ dateinterval.length ] = dt ; ...
Deep understanding : How code structure affects the content of date arrays created with loops
JS
This I just created a div . and I give a White-space : Normal function for word wrapping when I type the contents . This function is working in Chrome , Opera and Safari Browser . But the words are not wrapping in Mozilla Firefox and Edge browser . And also I tried the Word-wrap : break-word function . This is also not...
< div class = `` list-name-field '' id = `` SAVE_LIST '' style = `` white-space : normal ; width : 240px ; min-height : 35px ; border-radius : 3px ; margin-left : auto ; margin-right : auto ; background-color : # ccc ; margin-top : 5px ; `` contenteditable = `` true '' data-placeholder = `` Add a List ... '' > < /div >
Word wrapping is not working
JS
If I have an ES6 class like : this.bar should be re-evaluated each time echo is called.Are there any potential issues that could come from this usage ?
class Foo { constructor ( bar ) { this.bar = bar ; } echo ( value=this.bar ) { return value ; } } f = new Foo ( 10 ) ; f.echo ( ) ; > > 10f.bar = 99 ; f.echo ( ) ; > > 99
Are there any issues with using a this.variable as an argument default in Javascript ?
JS
I am using a .zip file with thousands of geographical coordinates and converting to base64.I can convert the file to base64 , the problem is to save the result of this variable for later use.I 'm trying to use setState to save the variable 's value but nothing happens.Can you tell me what I 'm doing wrong ? Here 's my ...
const [ zipFile , setZipFile ] = useState ( `` '' ) ; const [ base64 , setBase64 ] = useState ( `` '' ) ; const getBase64 = ( file , cb ) = > { let reader = new FileReader ( ) ; reader.readAsDataURL ( file ) ; reader.onload = function ( ) { cb ( reader.result ) ; } ; reader.onerror = function ( error ) { } ; } ; const ...
How to save the value of a variable converted to base64 ?
JS
I 've got the following code , so I can get parameters from a url.However one of the parameters has a & sign in the text resulting in the text after it being cuts off . how do I get the & sign to display with the corresponding text after it ? Example URL = ? Club % 20Plus % 20Health % 20 & % 20Fitness ( I ca n't change...
function getUrlVars ( ) { var vars = { } ; var parts = window.location.href.replace ( / [ ? & ] + ( [ ^= & ] + ) = ( [ ^ & ] * ) /gi , function ( m , key , value ) { vars [ key ] = value ; } ) ; return vars ; } var cmp = getUrlVars ( ) [ `` cmp '' ] ; document.getElementById ( `` currentMemberPackage '' ) .value = cmp ...
Parse URL parameters with `` & '' characters without an `` = '' after
JS
I am trying to teach beginners javascript . Here is what I am trying to do : I will give them a snippet of code such as a function with something incorrect : They will submit the code back to me.I would like to write some test cases which would run on their code and evaluate if they are correct.Does it make sense for t...
const square = function ( x ) { return x + x ; // Wrong ! This will double the number , not square them . } ;
How to test small snippets of javascript code without a web browser ?
JS
I 'm having a problem with my searchbar component . When performing a search , the request is successful and we get the desired display , however if we want to do a new search over it we automatically return to the main menu during typing . Can you tell me how to keep the display of the previous search without returnin...
import React , { Component } from 'react'import ReactDOM from 'react-dom'import axios from 'axios'class App extends Component { constructor ( props ) { super ( props ) this.state = { pokemon : `` , resultDatas : `` , search : false , whiteList : [ ] , error : '' } this.handleChange = this.handleChange.bind ( this ) thi...
Prevent rerender home menu while typing
JS
I 'm currently using this to format an input text to have `` - '' after two characters and it replaces characters that are not `` a-f '' or `` 0-9 '' with `` '' . I want it to also detect if the user writes `` : '' and replace it with `` - '' , so it becomes impossible to write `` : '' . Not sure how to accomplish this...
var macAddress = document.getElementById ( `` macInput '' ) ; function formatMAC ( e ) { var r = / ( [ a-f0-9 ] { 2 } ) ( [ a-f0-9 ] { 2 } ) /i , str = e.target.value.replace ( / [ ^a-f0-9 ] /ig , `` '' ) ; while ( r.test ( str ) ) { str = str.replace ( r , ' $ 1 ' + '- ' + ' $ 2 ' ) ; } e.target.value = str.slice ( 0 ...
Replace `` : '' with `` - '' while also formatting mac address
JS
In TypeScript/Javscript , how do I check if class B extends class AAnswer : Couple of ways to do this . Thanks to @ Daniel and @ AviatorXNot sure whats the most TypeScript idiomatic way to do it or if there are any missing edge cases but worked for my use case
class A { ... } class B extends A { ... } assert ( B extends A ) // How to do something like this ? B.prototype instanceof A // trueObject.getPrototypeOf ( B ) === A // trueReflect.getPrototypeOf ( B ) === A // true
How to check if a class B extends A during runtime
JS
I have strings likewhere the ___could be anywhere in the string.What is the easiest way to split them at any single _ but not at ___ ?
A_B_C_DA_B___C_D
Split at single separator occurrence
JS
I discovered a peculiarity in JavaScript ( or perhaps my browser 's idea of it ) : Running the above with Firebug console enabled , I get : Why does the string automatically get turned into a weird object before becoming the this passed to foo ? The reason I call it a weird object is because jQuery chokes on it . For e...
var s = `` Hello , world '' ; function foo ( arg ) { console.log ( arg ) ; console.log ( this ) ; } foo.call ( s , s ) ; Hello , worldString { 0= '' H '' , 1= '' e '' , more ... } $ .each ( [ `` one '' , `` two '' , `` three '' ] , function ( i , x ) { $ ( ' < p > < /p > ' ) .text ( x ) .appendTo ( 'body ' ) ; // Works...
Why does a string get mutilated when it becomes ` this ` ?
JS
What is wrong with this expression ? I 'm getting this error :
[ ' a ' , ' b ' ] .map ( ( x ) = > { [ x ] : x } ) Uncaught SyntaxError : Unexpected token :
javascript object literal dynamic key SyntaxError
JS
need help , want to spin the image and after 3 sec it must stop with random dergree ( from 360 to 10800 ) . it starts spin when I click it from the last position . when the image stops , it appears an area with RANDOM citation from my massive . it must be something like `` spin the bottle '' please help , I 've got som...
.wheel { animation : wheel 3s .5s ; animation-fill-mode : both ; } @ keyframes wheel { from { transform : rotate ( 0 ) ; } to { transform : rotate ( 10800deg ) ; } } < head > < link rel= '' stylesheet '' href= '' bottle.css '' > < script src= '' bottle.js '' > < /script > < /head > < img id= '' wheel '' class= '' wheel...
Random in CSS or JS
JS
I was working toward a solution for this recent post : Repeating a function using array of values and in doing so , I stitched together the following piece of code.I run this and not surprisingly the following error message is returned : Cross-Origin Request Blocked : The Same Origin Policy disallows reading the remote...
< script src= '' https : //code.jquery.com/jquery-1.11.3.min.js '' > < /script > < script > var name_list = [ 'mike ' , 'steve ' , 'sean ' , 'roger ' ] ; var successAction = function ( name ) { console.log ( name ) ; } name_list.forEach ( function ( name ) { jQuery.ajax ( { type : `` GET '' , url : `` https : //www.goo...
ajax error results in success function call
JS
I have an external SDK written in JavaScript which I am using . One of these modules , Blob is new-able , but also exposes an enum FooEnum ( members Bar and Baz ) .The code for using this SDK in JavaScript is like so : I am now trying to write an interface that I can cast this SDK to in order to give me some type safet...
const blobInstance = new Sdk.Blob ( ) ; const fooType = Sdk.Blob.FooEnum.Baz ; interface BlobInterface { } enum Foo { Bar , Baz } interface Sdk { Blob : { new ( ) : BlobInterface ; FooEnum : Foo ; } }
TypeScript newable and enum reference
JS
Kyle example is about chunking data ( when is so big ) by asynchronous events and make events interleave in the event loop queue , that part i could n't get : The example from book : I could not get that part , my mind can not accept that this could make code perform better , would n't that cause data from two arrays t...
var res = [ ] ; // ` response ( .. ) ` receives array of results from the Ajax callfunction response ( data ) { var chunk = data.splice ( 0 , 1000 ) ; res = res.concat ( chunk.map ( function ( val ) { return val * 2 ; } ) ) ; if ( data.length > 0 ) { setTimeout ( function ( ) { response ( data ) ; } , 0 ) ; } } // ajax...
You Do n't Know JS : Async and Performance - cooperative concurrency ?
JS
This code new Function ( 'fn ' , 'fn ( ) ' ) creates anonymous function which has param and ( in this case the param is a function ) executed.Doing console.log ( new Function ( 'fn ' , 'fn ( ) ' ) ) shows the output : Now , the docs states : Note : Functions created with the Function constructor do not create closures ...
function anonymous ( fn ) { fn ( ) } var a = 44 ; function myFunc ( ) { var a = 1 ; function f ( ) { alert ( a ) } new Function ( 'fn ' , 'fn ( ) ' ) ( f ) ; } myFunc ( ) ;
Javascript 's Function constructor - scope issues ?
JS
In the following code , when $ ( this ) is called , does jQuery re-query the DOM as though a selector has been passed to it ( using some property of the object as a selector ) , or does jQuery retain the previously returned object ?
$ ( '.someButton ' ) .on ( 'click ' , function ( ) { $ ( this ) .remove ( ) ; // Is this another lookup , or just a wrapper for the previously returned object ? } ) ;
Does jQuery re-query the DOM when $ ( this ) is called ?
JS
I 'm trying to fit dot points on the line with area chart shape , however it does n't fit . I assume this is due to .curve using d3.curveBasis . Here is my approach :
data = [ { `` login_date '' : `` 2017-09-24 '' , `` unique_user_count '' : 2 , `` total_login_count '' : 2 } , { `` login_date '' : `` 2017-09-25 '' , `` unique_user_count '' : 25 , `` total_login_count '' : 46 } , { `` login_date '' : `` 2017-09-26 '' , `` unique_user_count '' : 31 , `` total_login_count '' : 74 } , {...
Circle points are not aligned with area shape
JS
How do I store the final value of balance amount that is being input ? HTMLJSPlease help me to solve this !
< div id= '' balance_amount '' > balance amount : < input type= '' number '' id= '' balance-amount-input '' name= '' balance_amount '' value='+balance_amount+ ' > < /div > $ ( 'body ' ) .on ( 'input ' , ' # balance-amount-input ' , function ( ) { $ ( '.jconfirm # error-msg ' ) .hide ( ) ; var balance_amount_tmp= $ ( th...
Store final value after being changed jQuery
JS
This question may be answered elsewhere but I was n't even sure how to begin searching for the answer . I 'm new to JavaScript so this one is a struggle for me to understand.Given the following code : When I pass the following into the console : I get what I expect , that is , 15 . Likewise with any number , it will be...
function multiple ( n ) { function f ( x ) { return x * n ; } return f ; } var triple = multiple ( 3 ) ; var quadruple = multiple ( 4 ) ; console.log ( triple ( 5 ) ) ; f ( x ) { return x * n ; } f ( x ) { return x * 3 ; } var triple = multiple ( 3 ) ;
Returning a function Chrome Dev tools
JS
I am trying to push a ingredient to a list of array . This ingredient is an object and has its id from uuid or any library and an ingredient value of whatever the user types on the input.I wrote the simplest example of it in a single function so its clear to understand the core of my doubt.How can I delete the item by ...
let ingredients = [ ] document.querySelector ( ' # ingredients-input ' ) .addEventListener ( 'change ' , ( e ) = > { e.preventDefault ( ) const id = uuid ( ) ingredients.push ( { id : id , title : e.target.value } ) const ingredientUl = document.createElement ( ' p ' ) const removeButton = document.createElement ( 'but...
Javascript dynamic button to delete item by id and delete himself ( infinite loop )
JS
I have a dynamically built table that ends up with the below code ( with example values ) : I am trying to highlight the row that is been hovered over using the below CSS : For some reason , this changes the background of what would be the `` < td > '' element , for example , will just highlight Value1 , Value2 or Valu...
< table id= '' patientTable '' class= '' display '' cellspacing= '' 0 '' width= '' 100 % '' > < thead id= '' TableHeader '' > < tr > < th > Value1 < /th > < th > Value2 < /th > < th > Value3 < /th > < /tr > < /thead > < tbody id= '' tableContent '' > < tr class= '' clickable row_0 '' onclick= '' selectPatient ( 10001 )...
Highlighting Table Rows
JS
I am having an issue with jQuery at the moment when it comes to the children of an element that has been dynamically pulled in with AJAX.So I have the following statement : However this does not work for some reason , when I click the children of the .Select-menu-outer element nothing happens.If I use the following sta...
$ ( '.Select-menu-outer ' ) .children ( ) .click ( function ( ) { console.log ( `` tiggered '' ) ; } ) ; $ ( document ) .on ( `` click '' , '.Select-menu-outer ' , function ( ) { console.log ( `` tiggered '' ) ; } ) ;
On Click Children Dynamic Content
JS
Why does the following statement : display the following outputand not a simple : Is this behavior built-in to the interpreter or is there a way to detect the type of reference passed ?
( function ( ) { console.log ( this ) ; } ) .apply ( String ( `` hello '' ) ) ; String { 0 : `` h '' , 1 : `` e '' , 2 : `` l '' , 3 : `` l '' , 4 : `` o '' , length : 5 } hello
Does console.log treat 'this ' differently ?
JS
An array contains objects with property `` title '' which contains lower-casing text with _ . Need to change the title by splitting ' _ ' and need to capitalize first letter after every space . I can change all the title casing to upper case but I need only the first letter after space should be capitalizedExpected : A...
const listData = [ { `` title '' : `` some_id '' , `` dataTypes '' : `` character varying ( 65535 ) '' } , { `` title '' : `` some_value '' , `` dataTypes '' : `` character varying ( 65535 ) '' } ] const newData = [ ] listData.map ( el = > newData.push ( { `` title '' : el.title.toUpperCase ( ) .split ( ' _ ' ) .join (...
Change the casing title of the object inside an array
JS
Everywhere I saw an implementation of singleton in javascript in a such manner : Here we can see that it returns a function which we must call in order to get an object . Question : Why we ca n't just write like this : Somebody will say that reason is for inheritance support . However , I do n't see a difference . Anyw...
var Singleton = ( function ( ) { var instance ; function createInstance ( ) { var object = new Object ( `` I am the instance '' ) ; return object ; } return { getInstance : function ( ) { if ( ! instance ) { instance = createInstance ( ) ; } return instance ; } } ; } ) ( ) ; var Singleton = ( function ( ) { function pr...
Why Javascript Singleton is written like this ?
JS
I have a use case where there comes a JSON response from backend in the form as follows : I need to remove all objects that has power == 0 . It 's easy to use filter on simple collection of arrays , but there might be cases where any n number of childs can contain n number of childs in it . Thanks in advance !
[ { `` name '' : `` cab '' , `` child '' : [ { `` name '' : `` def '' , `` child '' : [ { `` name '' : `` ghi '' , `` power '' : `` 0.00 '' , `` isParent '' : false } ] , `` power '' : `` 1.23 '' , `` isParent '' : true } ] , `` power '' : `` 1.1 '' , `` isParent '' : true } , { `` name '' : `` hhi '' , `` child '' : [...
Remove all arrays that has power == 0
JS
When I call thisI want it to print Harry Potter ( not Bob ) which it does above , however this : Now looks for this.book ( which is null ) where it should be looking for this.book2How can I reference the variable ?
var name = `` Bob '' ; var book = { name : `` Harry Potter '' , writeName : function ( ) { return function ( ) { document.writeln ( this.book.name ) ; } } } ; book.writeName ( ) ( ) ; var book2 = book ; book = null ; book2.writeName ( ) ( ) ;
Javascript scope and variables
JS
I use following code to display tabs . However I am failing to understand why js throws an error . Function opentab accepts 2 arguments ( id of contentab and id of button ) . It seems there is some problem in last row of js because it fails to add class `` active '' to clicked button . Can anybody help ? Thank you .
function opentab ( tabname , evt ) { var i , tabcontent , tablinks ; tabcontent = document.getElementsByClassName ( `` tabcontent '' ) ; for ( i = 0 ; i < tabcontent.length ; i++ ) { tabcontent [ i ] .style.display = `` none '' ; } tablinks = document.getElementsByClassName ( `` tablinks '' ) ; for ( i = 0 ; i < tablin...
getElementById ( ... ) is null - function with 2 variables
JS
Here is a little code snippet : I 'm curious to know if using setState in every iteration of a forEach loop is a bad idea or not . I 'm suspecting that it impacts performance , but I 'd like to know for sure because this seemed like the simplest solution to this problem .
async componentDidMount ( ) { ... this.state.postList.forEach ( element = > { this.fetchItem ( element ) ; } ) ; } async fetchItem ( query ) { ... this.setState ( previousState = > { const list = [ ... previousState.data , data ] ; return { data : list } ; } ) ; }
Is using setState in every iteration of a loop bad practice ?
JS
In TypeScript , there 's a pre-defined type called Partial < T > . It is defines like this : Apparently , the index signature is marked as optional , and this works . If I try to do the same thing like this : TypeScript complains about the ? . Is this because interfaces may not contain optional fields , or what is the ...
type Partial < T > = { [ P in keyof T ] ? : T [ P ] ; } interface IDictionary < T > { [ key : string ] ? : T }
Why ca n't this index signature be optional ?
JS
I 'm trying to make a left side navigation bar where by-default categories are listed and while clicking on a category , the subcategories are shown under it ( in sort expanding sub-menu ) . I 'm working in Django and relevant portions of my code are below . When I include the JS code , none of the links on the page wo...
{ % block theme_script % } < script src= '' { % static `` pinax/js/theme.js `` % } '' > < /script > < script > $ ( function ( ) { $ ( `` .nav-collapse88 '' ) .hide ( ) ; $ ( `` .nav-collapse89 a '' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( `` .nav-collapse88 '' , $ ( this ) .parent ( ) ) .slideToggle ( ) ;...
Submenu refuses to open on click
JS
I have a function : And two calls . First : Second : Is there any possible way to tell , from within the hello function , whether param was passed as a var or as a literal value ? NOTICE : I am not trying to solve a problem by this . There are many workarounds of course , I merely wanted to create a nice looking loggin...
function hello ( param ) { console.log ( 'param is '+param ) ; } hello ( 123 ) var a=123 ; hello ( a ) ;
Is there a way to tell whether a function parameter was passed as either a literal or as a variable ?
JS
the function below simply returns the smallest element in the given array using a reduce function . However , I quickly realized that the code below would throw a TypeError if the given array is empty : So I handled it by throwing in a quick if statement before the reduce ( ) method , as shown below . I 'm wondering , ...
function findSmallestElement ( arr ) { return arr.reduce ( ( a , b ) = > a < b ? a : b ) ; //throws TypeError if arr is an empty array } function findSmallestElement ( arr ) { if ( arr.length === 0 ) return 0 ; return arr.reduce ( ( a , b ) = > a < b ? a : b ) ; }
Better way to write this JS reduce ( ) code ?
JS
I want to find and update the value of a quantity to 3 where my id is `` 5cc6d9737760963ea07de411 '' my data : i tried : but it 's not working .
[ { `` products '' : [ { `` id '' : `` 5cc6d9737760963ea07de411 '' , `` quantity '' : 1 , `` totalPrice '' : 100 , } , { `` id '' : `` 5cc6d9737760963ea07de412 '' , `` quantity '' : 2 , `` totalPrice '' : 200 , } ] , `` isCompleted '' : false , `` _id '' : `` 5cc7e4096d7c2c1f03570a2f '' } , { `` products '' : [ { `` id...
Find and Update nested level
JS
'For In ' can traverse Array ( value/properties/function ) .The result will be : why does native function like 'toString'/'split ' not be printed ? what is the difference ? In my mind , they ( con and toString ) all belong to the prototype of Array .
let arr = [ 1,2,3,4 ] ; arr.__proto__.con = function ( ) { console.log ( 'from array ' ) ; } for ( let item in arr ) { console.log ( item ) ; } 1,2,3,4 , con
The difference between customize function and native function in prototype
JS
I want to know why the last one turns false.And `` 20a '' transforms to what before comparing .
console.log ( `` 20 '' > 10 ) ; //true console.log ( `` 20a '' > '' 10 '' ) ; //true console.log ( `` 20a '' > 10 ) ; //false
how a string object transforms when compared ?
JS
I 'm trying to match this dataCombien ? Lorem ipsum . Lorem ipsum . Lorem ipsum . Lorem ipsum.Lorem ipsum . Lorem ipsum . Lorem ipsum . Lorem ipsum.Lorem ipsum . Lorem ipsum . Lorem ipsum . Lorem ipsum . Lorem ipsum.Combien 2 ? Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ip...
Question 1 = CombienAnswer 1 = Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum.Lorem ipsum . ^ ( .+ ) \xA0* ( ? =\ ? ) \n* ^ ( .+ ) \xA0* ( ? ! \ ? ) $
How to parse multiple line complex regex pattern ?