Total Pageviews

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

2018/07/13

[JavaScript] How to set an array of data to textarea ?

Problem
I have a textarea as bellows:
   <textarea class='form-control' id='sentencesToLabeledData' name='sentencesToLabeledData' rows='10' cols='50'> </textarea>

How to set an array of data totextarea? And each element should add new line character

How-To
An array has a method to glue all elements together, Array.join. Without an argument, it would use a comma (,) as glue. To put every element on a new line, use the newline character (\n).
   // entity.sentences is an array of String
   if (entity.sentences != null && entity.sentences.length > 0){
       // apply Array.join to set new line character to each array element
       document.getElementById("sentencesToLabeledData").value = entity.sentences.join("\n");
   }



2018/07/12

[JavaScript] How to convert textarea into an array?

Problem
I have a textarea as bellows:
   <textarea class='form-control' id='sentencesToLabeledData' name='sentencesToLabeledData' rows='10' cols='50'> </textarea>

I would like to get its value and convert into an array. How to do it?

How-To
Here has two steps to fulfill this requirement:
   // Step 1. get the value of textarea
   var sentencesToLabeledData = document.getElementById("sentencesToLabeledData").value;
   // Step 2. split the value of textarea by \n, then it will convert into an array
   var sentenceArray = sentencesToLabeledData.split('\n');



2018/06/11

[JavaScript] How to get selected value from a drop-down list that allows multiple selections ?

Problem
Assume I have a drop-down list that allows multiple selections.
1
2
3
4
5
6
7
   <select class="form-control" multiple id="importIntentList" 
           name="importIntentList" style="height: 100%;" size="20">
      <option value="1">A</option>
      <option value="2">B</option>
      <option value="3">C</option>
      <option value="4">D</option>
   </select>

I try to get selected value from the drop-down list, how to do it?


How-To
Here has code snippet to get values from the multi-selected drop-down list and push values into array:
1
2
3
4
5
6
7
   var intentSelectedOptions = [];
   var items = document.getElementById("importIntentList");
   for (var i = 0; i < items.options.length; i++) {
       if (items.options[i].selected == true) {
           intentSelectedOptions.push(items.options[i].value);
       }
   }


2018/05/06

[JavaScript] Utilize window.getSelection to get selected text

Problem
If I would like to get the selected text from a TextField via JavaScript, how to do it?

How-To

You can make good use of window.getSelection to fulfill this requirement.

HTML code snippet:

       <div class="row">
           <div class="col-sm-offset-1 col-sm-10">
             <div class="form-group">
               <label for="operaName" class="control-label">連續劇</label>
               <input type="text" class="form-control input-lg" id="operaName" data-ng-model="operaName" 
                      data-ng-mouseup="showOperaSelectedText()" >
             </div>
             <div class="form-group">
              <label class="control-label">起訖</label>
              <span> {{operaNameFromIndex}} ~ {{operaNameToIndex}}</span>
             </div>
             <div class="form-group">
                 <label class="control-label">選擇文字</label>
                 <span> {{operaNameSelected}}</span>
             </div>
           </div>
       </div>


JavaScript code snippet:
     $scope.operaName = "又,吳海英";
     $scope.operaNameFromIndex = 0;
     $scope.operaNameToIndex = 0;
     $scope.operaNameSelected = '';
      
     $scope.showOperaSelectedText = function() {
     // if selected
     if (window.getSelection) {
          // get selected text
          $scope.operaNameSelected = window.getSelection().toString();
          // get from index
          $scope.operaNameFromIndex = $('#operaName').prop('selectionStart');
          // get end index
         $scope.operaNameToIndex = $('#operaName').prop('selectionEnd');
         }
     }


Screenshot:


2018/04/10

[JavaScript] Remove an item from array

Scenario
Assume I have an array of data in $scope.tab2.sentence.entities
I would like to remove an item from array based on the value which I provide, how to do it?


How-To

You can utilize splice to fulfill the requirement.
Here has the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 $scope.removeTab2Entity = function(entity) {
      var index;
      for (var i = 0; i < $scope.tab2.sentence.entities.length; i++) {
          if ($scope.tab2.sentence.entities[i].value == entity.value) {
              index = i;
              break;
          }
      }
      $scope.tab2.sentence.entities.splice(index, 1);
  }

splice syntax and its parameter information are as bellows:

Reference
[1] https://www.w3schools.com/jsref/jsref_splice.asp

2015/11/19

[AngularJS] Round to at most 2 decimal places in ng-grid CellFilter

Problem
I utilize ng-grid to implement the grid as bellows:

The value of 利率 has 4 decimal places, customer ask to change to 2 decimal places.
The ng-grid definition is as following:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 $scope.itemGrid = {
            multiSelect : false,
   data : 'itemData',
            showFooter : false,
            keepLastSelected: false,
   enableColumnResize: true,
            columnDefs : [ {
                field : 'fundName',
                displayName : '借入基金專戶',
                width : '21%',
                cellClass : "text-left",
                cellFilter:'dbm035eFundFilter:row.entity.toFundName : row.entity.debtType=="B"'
            }, {
                field : 'toFundName',
                displayName : '借出基金專戶',
                width : '21%',
                cellClass : "text-left",
                cellFilter:'dbm035eFundFilter:row.entity.fundName : row.entity.debtType=="B"'
            }, {
                field : 'debtDateB',
                displayName : '調借起日',
                width : '10%',
                cellClass : "text-left",
                cellFilter:"dbm035eToStringFilter|dateFilter" 
            }, {
                field : "debtDateE",
                displayName : "調借迄日",
                width : '10%',
                cellClass : "text-left",
                cellFilter:"dbm035eToStringFilter|dateFilter" 
            }, {
                field : "debtAmt",
                displayName : "調借金額",
                width : '10%',
                cellClass : "text-right",
                cellFilter:"dbm035eAmountFilter | number"
            }, {
                field : "debtRate",
                displayName : "利率",
                width : '8%',
                cellClass : "text-right"
            }, {
                field : "remark",
                displayName : "備註",
                width : '20%',
                cellClass : "text-left"
            }
   //....
 }];


How-To
Step 1. Create a cellFilter to debtRate field
1
2
3
4
5
    app.filter('dbm035eRateFilter', function() {
        return function(input) {
            return null==input?null:(Math.round(input * 100)/100);
        };
    });

Step 2. Add this cellFilter to debtRate field
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 $scope.itemGrid = {
            multiSelect : false,
   data : 'itemData',
            showFooter : false,
            keepLastSelected: false,
   enableColumnResize: true,
            columnDefs : [ {
                field : 'fundName',
                displayName : '借入基金專戶',
                width : '21%',
                cellClass : "text-left",
                cellFilter:'dbm035eFundFilter:row.entity.toFundName : row.entity.debtType=="B"'
            }, {
                field : 'toFundName',
                displayName : '借出基金專戶',
                width : '21%',
                cellClass : "text-left",
                cellFilter:'dbm035eFundFilter:row.entity.fundName : row.entity.debtType=="B"'
            }, {
                field : 'debtDateB',
                displayName : '調借起日',
                width : '10%',
                cellClass : "text-left",
                cellFilter:"dbm035eToStringFilter|dateFilter" 
            }, {
                field : "debtDateE",
                displayName : "調借迄日",
                width : '10%',
                cellClass : "text-left",
                cellFilter:"dbm035eToStringFilter|dateFilter" 
            }, {
                field : "debtAmt",
                displayName : "調借金額",
                width : '10%',
                cellClass : "text-right",
                cellFilter:"dbm035eAmountFilter | number"
            }, {
                field : "debtRate",
                displayName : "利率",
                width : '8%',
                cellClass : "text-right",
                cellFilter:"dbm035eRateFilter" 
            }, {
                field : "remark",
                displayName : "備註",
                width : '20%',
                cellClass : "text-left"
            }
   //....
 }];

Check the result


Reference
[1] http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript

2014/05/09

java.lang.NullPointerException: Cannot find parameter "json" from request.


Problem
I found out I fail to execute print functions in every function in my system.


And the console throw this exception message:
 java.lang.NullPointerException: Cannot find parameter "json" from request.  
   at java.util.Objects.requireNonNull(Objects.java:226) ~[na:1.7.0_25]  
   at com.cht.commons.web.resolver.JsonParamResolver.resolveArgument(JsonParamResolver.java:34) ~[cht-commons-web-0.1.0-SNAPSHOT.jar:0.1.0-SNAPSHOT]  

Root Cause
As I check its request header, it submit nothing



It result from my request had been blocked by AdBlock (Chrome Plug-in), which I installed yesterday. That's why I failed to execute every print function today.

As I disabled this Chrome plug-in, AdBlock, and check its request header again. We can see request header had submitted data.

Finally, my report function had recovered.





2014/03/13

Error: ng:areq Bad Argument

Problem
I have a html page with 2 tabs.

As I entered this page, it occurred javascript errors with "Error: ng:areq" and link to this page: http://docs.angularjs.org/error/ng/areq?p0=fms435rTab1Controller&p1=not%20a%20function,%20got%20undefined


Trace the Problem
There are three html files to consist of this page. Each html file have its own JavaScript file, and will be imported by mail page.

fms435r.js
 (function() {  
   var app = angular.module("fms435rApp", [ 'ntaCommonModule' ]);  
 })();  

fms435rTab1.js
(function() {  
   var app = angular.module("fms435rApp");  
   app.factory('fms435rService', function(cResource) {  
     return {};  
   });  
   app.controller('fms435rTab1Controller', function($scope, fms435rService,  
       stateManager, alerter, userHolder) {      
   });  
 })(); 

fms435rTab2.js
 (function() {  
   var app = angular.module("fms435rApp", [ 'ntaCommonModule' ]);  
   app.factory('fms435rService', function(cResource) {  
     return {};  
   });  
   app.controller('fms435rTab2Controller', function($scope, fms435rService,  
       stateManager, alerter, userHolder) {  
   });  
 })();  

Root Cause
The problem result from fms435rTab2.js. 
It misuse angular.module, because it create a new module, not to retrieve.
Therefore, you should fix it as bellows:
 (function() {  
   var app = angular.module("fms435rApp");  
   app.factory('fms435rService', function(cResource) {  
     return {};  
   });  
   app.controller('fms435rTab2Controller', function($scope, fms435rService,  
       stateManager, alerter, userHolder) {  
   });  
 })(); 

Here is the syntax
ParamTypeDetails
namestring
The name of the module to create or retrieve.
requires
(optional)
Array.=
If specified then new module is being created.
If unspecified then the module is being retrieved for
further configuration.
configFnFunction
Optional configuration function for the module.
 Same as Module#config().

Reference
[1] http://docs.angularjs.org/api/ng/function/angular.module

2014/02/20

常用JavaScript function整理


 //取得今年民國年  
 function getCurrentYear(){  
    var date = new Date();  
    return date.getFullYear() - 1911;    
 }  
 //取得當下月份  
 function getCurrentMonth(){  
   var date = new Date();  
   return date.getMonth()+1;  
 }  
 //取得當下日期  
 function getCurrentDate(){  
   var date = new Date();  
   return date.getDate();  
 }  
 //取得當月的第一天(民國年+月+日)  
 function getFirstDateOfCurrentMonth(){  
   var date = new Date();  
   var currentYear = date.getFullYear() - 1911;  
   var currentMonth = date.getMonth()+1;  
   return leftPad(String(currentYear), 3) +  
       leftPad(String(currentMonth), 2)+  
       leftPad('1', 2);  
 }  
 //取得當天日期  
 function getCurrentDate(){  
   var date = new Date();  
   var currentYear = date.getFullYear() - 1911;  
   var currentMonth = date.getMonth()+1;  
   var currentDate = date.getDate();  
   return leftPad(String(currentYear), 3) +  
       leftPad(String(currentMonth), 2)+  
       leftPad(currentDate, 2);  
 }  
 //取得當月最後一天  
 function getEndDayInMonth(year, month){  
   return XDate.getDaysInMonth(year, parseInt(month)-1);  
 }  
 //減去指定年,如20141104減去2年,變成20121104  
 function minusYears(date, year){  
   return date.addYears(0 - parseInt(year), true).toString('yyyyMMdd');  
 }  
 //減去指定月,如20141104減去2個月,變成20140904  
 function minusMonths(date, month){  
   return date.addMonths(0 - parseInt(month), true).toString('yyyyMMdd');  
 }  
 //確認是否為數字  
 function isNumber(n) {  
    return !isNaN(parseFloat(n)) && isFinite(n);  
 }  
 //檢查是串是否不為空值且不為undefined  
 function isNotEmptyOrUndefined(str){  
  return str != '' && !angular.isUndefined(str) && str != null;    
 }  
 //檢查是否為空值且為undefined  
 function isEmptyOrUndefined(str){  
  return str == '' || angular.isUndefined(str) || str == null;    
 }  
 //檢查日期起迄,如起始日期為1021101,結束日期為1021103,其會回傳true;  
 //如起始日期為1021103,結束入其為1021101,其會回傳false  
 function isValidStartAndEndDate(startDate, endDate){  
   var isValid = false;  
   var startYear = parseInt(startDate.substring(0, 3))+1911;  
   var startMonth = parseInt(startDate.substring(3, 5)-1);  
   var startDay  = parseInt(startDate.substring(5, 7));  
   var endYear  = parseInt(endDate.substring(0, 3))+1911;  
   var endMonth  = parseInt(endDate.substring(3, 5)-1);  
   var endDay   = parseInt(endDate.substring(5, 7));  
   var sXdate = new XDate(startYear, startMonth, startDay);  
   var eXdate = new XDate(endYear, endMonth, endDay);  
   var diffDays = sXdate.diffDays(eXdate);  
   if(diffDays < 0){  
     isValid = false;  
   }else{  
     isValid = true;  
   }  
   return isValid;  
 }  
 //檢查日期起迄,如起始日期為1020101,結束日期為1020131,其會回傳true;  
 //如起始日期為1031103,結束入其為1021101,其會回傳false  
 function isValidStartAndEndYYYMM(startDate, endDate){  
   var isValid = false;  
   var startYear = parseInt(startDate.substring(0, 3))+1911;  
   var startMonth = parseInt(startDate.substring(3, 5)-1);  
   var startDay  = parseInt(startDate.substring(5, 7));  
   var endYear  = parseInt(endDate.substring(0, 3))+1911;  
   var endMonth  = parseInt(endDate.substring(3, 5)-1);  
   var endDay   = parseInt(endDate.substring(5, 7));  
   var sXdate = new XDate(startYear, startMonth, startDay);  
   var eXdate = new XDate(endYear, endMonth, endDay);  
   var diffDays = sXdate.diffMonths(eXdate);  
   if(diffDays < 0){  
     isValid = false;  
   }else{  
     isValid = true;  
   }  
   return isValid;  
 }  
 //西元轉民國,如20141104轉1021104  
 function convertFromWesternToChinse(western){  
   var year = parseInt(western.substring(0, 4))-1911;  
   var monthDate = western.substring(4, western.length);  
   return leftPad(String(year), 3)+monthDate;  
 }  
 //若未滿位,左邊補0  
 function leftPad(val, length) {  
   var str = '' + val;  
   while (str.length < length) {  
     str = '0' + str;  
   }  
   return str;  
 }  

註: 有用到xdate字眼的部分,要到 http://arshaw.com/xdate/ 這裡下載js檔