# 4 Javascript Sample

## 1 Add fireworks int form

```javascript
//Fireworks

(function webpackUniversalModuleDefinition(root, factory) {
    if (typeof exports === 'object' && typeof module === 'object') module.exports = factory();
    else if (typeof define === 'function' && define.amd) define([], factory);
    else if (typeof exports === 'object') exports["EFFECT"] = factory();
    else root["EFFECT"] = factory()
})(this,function() {
    return (function(modules) {
        var installedModules = {};
        function __webpack_require__(moduleId) {
            if (installedModules[moduleId]) return installedModules[moduleId].exports;
            var module = installedModules[moduleId] = {
                exports: {},
                id: moduleId,
                loaded: false
            };
            modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
            module.loaded = true;
            return module.exports
        }
        __webpack_require__.m = modules;
        __webpack_require__.c = installedModules;
        __webpack_require__.p = "";
        return __webpack_require__(0)
    })([function(module, exports, __webpack_require__) {
        'use strict';
        var canvas = document.createElement('canvas');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        canvas.style.cssText = 'position:fixed;top:0;left:0;pointer-events:none;z-index:999999';
        window.addEventListener('resize',
        function() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight
        });
        document.body.appendChild(canvas);
        var context = canvas.getContext('2d');
        var particles = [];
        var particlePointer = 0;
        EFFECT.shake = true;
        function getRandom(min, max) {
            return Math.random() * (max - min) + min
        }
        function getColor(el) {
            if (EFFECT.colorful) {
                var u = getRandom(0, 360);
                return 'hsla(' + getRandom(u - 10, u + 10) + ', 100%, ' + getRandom(50, 80) + '%, ' + 1 + ')'
            } else {
                return window.getComputedStyle(el).color
            }
        }
        function getCaret() {
            var el = document.activeElement;
            var bcr;
            if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && el.getAttribute('type') === 'text')) {
                var offset = __webpack_require__(1)(el, el.selectionStart);
                bcr = el.getBoundingClientRect();
                return {
                    x: offset.left + bcr.left,
                    y: offset.top + bcr.top,
                    color: getColor(el)
                }
            }
            var selection = window.getSelection();
            if (selection.rangeCount) {
                var range = selection.getRangeAt(0);
                var startNode = range.startContainer;
                if (startNode.nodeType === document.TEXT_NODE) {
                    startNode = startNode.parentNode
                }
                bcr = range.getBoundingClientRect();
                return {
                    x: bcr.left,
                    y: bcr.top,
                    color: getColor(startNode)
                }
            }
            return {
                x: 0,
                y: 0,
                color: 'transparent'
            }
        }
        function createParticle(x, y, color) {
            return {
                x: x,
                y: y,
                alpha: 1,
                color: color,
                velocity: {
                    x: -1 + Math.random() * 2,
                    y: -3.5 + Math.random() * 2
                }
            }
        }
        function EFFECT() {
            {
                var caret = getCaret();
                var numParticles = 5 + Math.round(Math.random() * 10);
                while (numParticles--) {
                    particles[particlePointer] = createParticle(caret.x, caret.y, caret.color);
                    particlePointer = (particlePointer + 1) % 500
                }
            } {
                if (EFFECT.shake) {
                    var intensity = 1 + 2 * Math.random();
                    var x = intensity * (Math.random() > 0.5 ? -1 : 1);
                    var y = intensity * (Math.random() > 0.5 ? -1 : 1);
                    document.body.style.marginLeft = x + 'px';
                    document.body.style.marginTop = y + 'px';
                    setTimeout(function() {
                        document.body.style.marginLeft = '';
                        document.body.style.marginTop = ''
                    },
                    75)
                }
            }
        };
        EFFECT.colorful = false;
        function loop() {
            requestAnimationFrame(loop);
            context.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < particles.length; ++i)
			{
                var particle = particles[i];
                if (particle.alpha <= 0.1) continue;
                particle.velocity.y += 0.075;
                particle.x += particle.velocity.x;
                particle.y += particle.velocity.y;
                particle.alpha *= 0.96;
                context.globalAlpha = particle.alpha;
                context.fillStyle = particle.color;
                context.fillRect(Math.round(particle.x - 1.5), Math.round(particle.y - 1.5), 3, 3);
            }
			//context.fillText("文字",particle.x,particle.y) //太频繁，文字会卡死固定位置
        }
        requestAnimationFrame(loop);
        module.exports = EFFECT
    },
    function(module, exports) {
        (function() {
            var properties = ['direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing', 'tabSize', 'MozTabSize'];
            var isFirefox = window.mozInnerScreenX != null;
            function getCaretCoordinates(element, position, options) {
                var debug = options && options.debug || false;
                if (debug) {
                    var el = document.querySelector('#input-textarea-caret-position-mirror-div');
                    if (el) {
                        el.parentNode.removeChild(el)
                    }
                }
                var div = document.createElement('div');
                div.id = 'input-textarea-caret-position-mirror-div';
                document.body.appendChild(div);
                var style = div.style;
                var computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle;
                style.whiteSpace = 'pre-wrap';
                if (element.nodeName !== 'INPUT') style.wordWrap = 'break-word';
                style.position = 'absolute';
                if (!debug) style.visibility = 'hidden';
                properties.forEach(function(prop) {
                    style[prop] = computed[prop]
                });
                if (isFirefox) {
                    if (element.scrollHeight > parseInt(computed.height)) style.overflowY = 'scroll'
                } else {
                    style.overflow = 'hidden'
                }
                div.textContent = element.value.substring(0, position);
                if (element.nodeName === 'INPUT') div.textContent = div.textContent.replace(/\s/g, "\u00a0");
                var span = document.createElement('span');
                span.textContent = element.value.substring(position) || '.';
                div.appendChild(span);
                var coordinates = {
                    top: span.offsetTop + parseInt(computed['borderTopWidth']),
                    left: span.offsetLeft + parseInt(computed['borderLeftWidth'])
                };
                if (debug) {
                    span.style.backgroundColor = '#aaa'
                } else {
                    document.body.removeChild(div)
                }
                return coordinates
            }
            if (typeof module != "undefined" && typeof module.exports != "undefined") {
                module.exports = getCaretCoordinates
            } else {
                window.getCaretCoordinates = getCaretCoordinates
            }
        } ())
    }])
});

    EFFECT.colorful = true;
    EFFECT.shake = true;
    document.body.addEventListener('input', EFFECT);
```

## 2 Form vote

```javascript
//Get main table field id
var fieldid1 = WfForm.convertFieldNameToId("bfb");//percentage
var fieldid2 = WfForm.convertFieldNameToId("fjqry");//Disagree person
var fieldid3 = WfForm.convertFieldNameToId("lztj");//Condition
var fieldid6 = WfForm.convertFieldNameToId("mxbh");//Detail table
var mx=WfForm.getFieldValue(fieldid6);;//Details table field it
var fieldid4 = WfForm.convertFieldNameToId("tpr", "detail_"+mx);//Vote person
var fieldid5 = WfForm.convertFieldNameToId("yj", "detail_"+mx);//Comments

var userid=WfForm.getBaseInfo().f_weaver_belongto_userid;

//WfForm.controlDetailRowDisplay("detail_"+mx, "all", true);
setTimeout(function(){
    $(".vote").show()
},1000);
//Check all detail table, hide non-current user's line
var rowArr1 = WfForm.getDetailAllRowIndexStr("detail_"+mx).split(",");

for(var i=0; i<rowArr1.length; i++){
    var rowIndex1 = rowArr1[i];
    if(rowIndex1 !== ""){
        var fieldvalue4=WfForm.getFieldValue(fieldid4+"_"+rowIndex1);//Get vote person's value

        if(userid!=fieldvalue4){
            WfForm.controlDetailRowDisplay("detail_"+mx, rowIndex1, true);
        }else{
            WfForm.controlDetailRowDisplay("detail_"+mx, rowIndex1, false);
            WfForm.changeFieldAttr(fieldid5+"_"+rowIndex1, 3);//Change vote comments as required
        }
    }
}
//Submit for verification and result calculation
WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, function(callback){
    var fieldvalue1 = WfForm.getFieldValue(fieldid1);//Get percentage
    var fieldvalue2 = WfForm.getFieldValue(fieldid2);//Get vote person
    if(fieldvalue1==null || fieldvalue1==""){
        alert("Please contact admin to set pass rate！")
    }else{
        var rowArr = WfForm.getDetailAllRowIndexStr("detail_"+mx).split(",");//Check details table
        var coun=rowArr.length;
        var countfieldid5=0;
        var check=false;
        for(var i=0; i<rowArr.length; i++){
            var rowIndex = rowArr[i];
            if(rowIndex !== ""){
                var fieldMark = "field111_"+rowIndex;    //Check details table
                var fieldvalue4=WfForm.getFieldValue(fieldid4+"_"+rowIndex);//Get vote person value
                var fieldvalue5=WfForm.getFieldValue(fieldid5+"_"+rowIndex);//Get vote comments
                if(fieldvalue5=="0"){
                    countfieldid5=parseInt(countfieldid5)+parseInt("1");
                }

                if(fieldvalue4==fieldvalue2 && fieldvalue5=="1"){
                    check=true;
                }
            }
            var tgl=(countfieldid5*1.00)/(coun*1.00);
            // console.log(countfieldid5)
            // console.log(coun)
            // console.log(tgl)
            var checktgl=false;
            if(tgl>=fieldvalue1){//Vote rate > Pass rate
                checktgl=true;
            }
            if(!check && checktgl){
                WfForm.changeFieldValue(fieldid3, {value:"0"});//Vote passed

            }else{
                WfForm.changeFieldValue(fieldid3, {value:"1"});//Vote failed
            }
        }
    }

    callback();
});
```

## 3 Simulate the click action to show workflow chart

```javascript
var baseFrame = $(window.parent.document).find(".tab_menu");
baseFrame.children().eq(1).children().eq(0).click(); //Show workflow chart
$(window.parent.document).find("#divWfPic").hide();  //Hide workflow chart
$(window.parent.document).find("#divWfBill").show();

///Set the workflow chart image field id as overflowPic
$(document).ready(function(){
	//Becuase take some time to generate the workflow chart, then need to extend the time
	setTimeout(function(){
		//find canvas
		var pic = $(window.parent.document.getElementById("piciframe")).contents().find("#mainArea");
		//generate the image
		var _img = document.createElement("img");
		_img.src = pic[0].toDataURL("image/png");
		$('#overflowPic').append(_img);
	}, 500);
});
```

## 4 Add placeholder

```javascript
jQuery(document).ready(function(){
	$("#field6387").attr("placeholder", "Please fill in counterparties");
});
```

## 5 Change tips text base on dropdown

```javascript
/// If the dropdown is 0, then hide tips
/// If the dropdown is 1, then change tips text as [Note: This is a testing tips, please double check]
/// Note: need to set the tips region class as promptText
jQuery(document).ready(function(){
	var _selectId = "field8581";
	if($("#" + _selectId).val() == 0){
		$(".promptText").parents("tr").eq(0).hide();
	} else {
		$(".promptText").text("[Note: This is a testing tips, please double check]");
	}
});
```

## 6 Check mobile phone number

```javascript
jQuery(document).ready(function(){
	checkCustomize = function(){
		var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;//Chinese Mobile Phone Number
		var isMob= /^0?1[3|4|5|8][0-9]\d{8}$/;// Chinese Telephone Number
		var isSingaporeNumber = /^\+65(6|8|9)\d{7}$/;
		var _val = $("#field7915").val();
		if(_val == "") return true;
		else if(isMob.test(_val) || isPhone.test(_val) || isSingaporeNumber(_val)) return true;
		else {
			alert("Please fill in the correct number");
			return false;
		}
	};
});
```

## 7 Begin date should not later than End date

```javascript
/* Begin date should not later than End date */

var beginTimeId = {id: "field7911", name: "Begin Date"}; //Begin Id
var endTimeId   = {id: "field7912", name: "End Date"}; //End Id

$(document).ready(function(){
	checkCustomize = checkChangeFunction; // Submit for check
	$("#" + beginTimeId.id).bindPropertyChange(function(){ checkChangeFunction(); });// Check begin date
	$("#" + endTimeId.id).bindPropertyChange(checkChangeFunction);  // Check end date
});

/// Check function
function checkChangeFunction(){
	var beginTime = new Date($("#" + beginTimeId.id).val()); //Convert to date type
	var endTime = new Date($("#" + endTimeId.id).val());     //Convert to date type
	return (beginTime > endTime) ?
		( alert(beginTimeId.name + " could not later than " + endTimeId.name), false ): ( true );
}


//---------------------------------------------------------------------------------------------------
/* Begin date should not later than End date */


var beginTimeId = {date: "field7911", time: "field8482"}; //Begin
var endTimeId   = {date: "field7912", time: "field8483"}; //End

$(document).ready(function(){
	checkCustomize = function (){
		var beginTime = new Date($("#" + beginTimeId.date).val() + " " +$("#" + beginTimeId.time).val()); //Convert to date type
		var endTime = new Date($("#" + endTimeId.date).val() + " " +$("#" + endTimeId.time).val());     //Convert to date type
		return (beginTime > endTime) ?
			( alert("Begin date should not later than end date"), false ): ( true );
	}; // Submit for check
});
```

## 8 Confirm current time and submit

```javascript
/* Confirm current time and submit  */

/// Main table with time, provide two button, confirm current time and submit, Get current time
/// Make Confirm current time and submit class as changeButton, add user define attribite submitNow as true
/// Make Get current Time field class as changeButton

var needWriteDateId = "7912"; //Date ID
var needWriteTimeId = "8483"; //Time ID

$(".changeButton").click(function(){
	//Change date value
	var time = new Date();
	$("#field" + needWriteDateId).val(getDateYMD(time));
	$("#field" + needWriteDateId + "span").text(getDateYMD(time));
	$("#field" + needWriteTimeId).val(getTimeHM(time));
	$("#field" + needWriteTimeId + "span").text(getTimeHM(time));

	//Trigger submit button
	if($(this).attr("submitNow")){
		setTimeout(function(){
			parent.bodyiframe.doSubmitBack(this);
			parent.hideRightClickMenu();
		}, 1000);
	}
});

///Convert _time as yyyy-mm-dd format
function getDateYMD(_time){
	var year = _time.getFullYear();
	var month = _time.getMonth()+1;
	var date = _time.getDate();

	return year + "-" + ((month < 10) ? ("0" + month): month) + "-" + ((date < 10) ? ("0" + date): date);
}

///Convert _time as hh:mm format
function getTimeHM(_time){
	var hours = _time.getHours();
	var minutes = _time.getMinutes();

	return ((hours < 10) ? ("0" + hours): hours) + ":" + ((minutes < 10) ? ("0" + minutes): minutes);
}
```

## 9 Default to get a date

```javascript
$(document).ready(function(){
	var _oldId = "field8444";
	var _newId = "field8464";

	$("#" + _newId).val($("#" + _oldId).val());
	$("#" + _newId + "span").text($("#" + _oldId + "span").text());
});
```

## 10 Time difference in hours

```javascript
/* Time difference in hours */

var beginTimeId = "field8482"; //Begin Time Id
var beginDateId = "field7911"; //Begin Date Id
var endTimeId   = "field8483"; //End Time Id
var endDateId   = "field7912"; //End Date Id

$(document).ready(function(){
	checkCustomize = function(){
		var beginTime = new Date($("#" + beginTimeId).val() + " " + $("#" + beginDateId).val());
		var endTime = new Date($("#" + endTimeId).val() + " " + $("#" + endDateId).val());

		var differTime = endTime - beginTime;            //Time difference in seconds
		var days = Math.floor(differTime / (3600*1000)); //Time difference in hours
		$("#field8170").val(days);
		return true;
	}
});
```

## 11 Update time per second

```javascript
/* Update time per second */

$(document).ready(function(){
	showtime();
	setInterval("showtime()",1000);
});
function showtime() {
	var date = new Date();
	var _text = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
	document.getElementById("field6321span").innerText = _text
	document.getElementById("field6321").value = _text
}
```

## 12 Check whether time 1 is within time 2, change the reminder text

```javascript
/* Check whether time 1 is within time 2, change the reminder text */

/// Note: change the tips reggion class as "prompText"
/// If time 1 is within time2, then hide the tips text
/// Else, change the tips text as [Note: Leave application date & time is different with real date & time]
jQuery(document).ready(function(){
	var _beginDateId1 = "field8566", _beginDateId2 = "field8586";
	var _beginTimeId1 = "field8567", _beginTimeId2 = "field8587";
	var _endDateId1   = "field8568", _endDateId2   = "field8588";
	var _endTimeId1   = "field8569", _endTimeId2   = "field8589";

	var isError = checkDate($("#" + _beginDateId1).val(), $("#" + _beginDateId2).val(), $("#" + _beginTimeId1).val(), $("#" + _beginTimeId2).val(), $("#" + _endDateId1).val(), $("#" + _endDateId2).val(), $("#" + _endTimeId1).val(), $("#" + _endTimeId2).val());
	if(!isError){
		$(".promptText").parents("tr").eq(0).hide();
	} else {
		$(".promptText").text("[Note: Leave application date & time is different with real date & time]");
	}
});

/// Check time 2 is within time 1
/// _beginDate1 _beginTime1 Time1 Begin Date & Time
/// _beginDate2 _beginTime2 Time2 Begin Date & Time
/// _endDate1 _endTime1 Time1 End Date & Time
/// _endDate2 _endTime2 Time1 End Date & Time
/// within the range, then return false, else return true
function checkDate(_beginDate1, _beginDate2, _beginTime1, _beginTime2, _endDate1, _endDate2, _endTime1, _endTime2){
	console.log(_beginDate1, _beginDate2, _beginTime1, _beginTime2, _endDate1, _endDate2, _endTime1, _endTime2);
	var isError = false;

	//Check start time
	if(_beginDate1 > _beginDate2) { isError = true;console.log(1); }
	else if(_beginDate1 == _beginDate2){
		if(_beginTime1 > _beginTime2) { isError = true;console.log(2); }
		console.log(3);
	}

	//Check End time
	if(_endDate1 < _endDate2) { isError = true; console.log(4); }
	else if(_endDate1 == _endDate2){
		if(_endTime1 < _endTime2) { isError = true; console.log(5); }
		console.log(6);
	}

	return isError;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ec9help.weaver.com.co/4-javascript-sample.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
