I wrote this in javascript to chat. Now I can call openChat with clicking a button and that works. But if I call it from onmessage-event, I get the
error: Uncaught TypeError: Cannot read property 'document' of
undefined
I'm new to javascript and I don't know, why I get this error?. Can somebody maybe help me?
Thanks:)
Thats the code:
var app = new Vue({
el: '#app',
data: {
busy: false,
roomId: 'POWebinar',
joinedRoom: false,
chatWirCB: false,
chatKundenCB: false,
microphoneWirCB: false,
microphoneKundenCB: false,
user: 'Benutzer',
},
methods: {
openChat: function () {
console.log("in fkt openChat");
win = window.open('', 'myconsole',
'scrollbars=1, width=450,height=500'
+ ',menubar=1'
+ ',toolbar=1'
+', location=1'
+ ',resizable=1')
win.document.writeln("<head><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'></head><body style='background-color:#ecf0f1'></body>");
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
win.document.title = "PatOrg - Live Chat";
win.document.getElementById('input-text-chat').onkeyup = function (e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
var a = new Date();
var b = a.getHours(); var c = a.getMinutes(); var d = a.getSeconds();
if (b < 10) { b = '0' + b; }
if (c < 10) { c = '0' + c; }
if (d < 10) { d = '0' + d; }
var time = b + ':' + c + ':' + d;
if (!this.value.length) return
console.log(this.value);
connection.send('<div id="chatSend" class="chat-OutputGET bubbleGET"> <font color="white">' + username + '(' + time + '): ' + this.value + '</font></div>');
console.log(username);
console.log('User (' + time + '): ' + this.value);
appendDIV('<div id="chatGet" class="chat-OutputSEND bubble"> <font color="white"> Ich (' + time + '): ' + this.value + '</font></div>');
this.value = '';
};
var chatContainer = win.document.getElementById('chat-output');
function appendDIV(event) {
if (event == "turnMicroOff" || event.data == "turnMicroOff" || event == "turnMicroOn" || event.data == "turnMicroOn" || event == "turnChatOn" || event.data == "turnChatOn" || event == "turnChatOff" || event.data == "turnChatOff") {
if (event == "turnMicroOff" || event.data == "turnMicroOff") {
console.log("audioID: " + audioID);
console.log("audioID: " + audioID);
for (i = 0; i < audioID.length; i++) {
connection.streamEvents[audioID[i]].stream.mute('audio');
}
}
else if (event == "turnMicroOn" || event.data == "turnMicroOn") {
console.log("audioID: " + audioID);
console.log("audioID: " + audioID);
for (i = 0; i < audioID.length; i++) {
connection.streamEvents[audioID[i]].stream.unmute('audio');
}
}
else if (event == "turnChatOn" || event.data == "turnChatOn") {
document.getElementById("btnChatOpen").style.visibility = "visible";
}
else if (event == "turnChatOff" || event.data == "turnChatOff") {
document.getElementById("btnChatOpen").style.visibility = "hidden";
}
}
else {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.appendChild(div);
div.tabIndex = 0;
div.focus();
win.document.getElementById('input-text-chat').focus();
emojify.run(win.document.getElementById('chat-output'));
}
}
connection.onmessage = appendDIV;
}
}
})
connection.onmessage = function (event) {
console.log(event.data);
if (event == "turnMicroOff" || event.data == "turnMicroOff") {
for (i = 0; i < audioID.length; i++) {
console.log("audioID: " + audioID[i]);
connection.streamEvents[audioID[i]].stream.mute('audio');
}
}
else if (event == "turnMicroOn" || event.data == "turnMicroOn") {
app.openChat();
for (i = 0; i < audioID.length; i++) {
console.log("audioID: " + audioID[i]);
connection.streamEvents[audioID[i]].stream.unmute('audio');
}
}
else if (event == "turnChatOn" || event.data == "turnChatOn") {
document.getElementById("btnChatOpen").style.visibility = "visible";
}
else if (event == "turnChatOff" || event.data == "turnChatOff") {
document.getElementById("btnChatOpen").style.visibility = "hidden";
}
}
Related
As a part of a before upload control, I check if added files actually match the filetype that their extension describes.
I do a filecheck using a hidden element. and if it fails, it gets removed after formdata append.
I check the files at the backend too, but I also want to check via File Reader process. All functions like createItems or readItems and so on, are working in all other cases, meaning that they return output of either null, true or false. While I get output from image and video files, audio files not at all. It should work.
The question is: Does the file reader read audio files differently compared to video and image files?
The following is only a tiny block of the actual code.
Now the question is: Why it doesn't return output on audio files?.
quest0 & quest1 are UI elements. Which is the element that I pull the files from.
reader is "new FileReader".
what.filecount is added while page init as readonly property.
readItems gives output on all kind off files,
However the UI html doesn't get updated if it is the file type is audio/?
for (var oD = 0; oD < what.files.length; oD++)
{
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) { return; }
if (file_s.exec(file) && !what.multiple) { pL = true; }
else
{
if (what.files.length > what.filecount)
{
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null)
{ quest0.innerHTML = ('too many files added. only ' + what.filecount + ' are allowed.'); }
return;
}
pL = true;
if ( !lastform.includes(what.form.id) ) { pL = false; }
}
if (what.files && what.files[oD] && pL == true)
{
if (file_prev != null)
{
if (file_prev.getAttribute('data-src') == '')
{file_prev.setAttribute('data-src', file_prev.src); }
file_prev.src = file_backsrc;
}
reader.onload = function(e)
{
init();
if (typeof file_prev === 'undefined')
{
if (quest1 != null) { quest1.innerHTML = 'Error occoured'; }
return;
}
if (file_p == 'img' || file_p == 'video' || file_p == 'audio')
{ file_prev.src = e.target.result; }
if (file_p == 'canvas') { /*not yet*/ }
kill.classList.remove('invisible');
if (quest1 != null) { quest1.innerHTML = 'file done'; }
}
reader.onerror = function(e)
{
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
}
function waitfor(arr)
{
if (arr == null || arr.length == 0) { return; }
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null)
{ quest1.innerHTML = 'processing ' + file_p; }
}
if (what.multiple)
{
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++)
{
var oB = what.files[oD], oB0, oB1;
if (oB.type.includes('im')) { file_p = 'img'; }
if (oB.type.includes('au')) { file_p = 'audio'; }
if (oB.type.includes('vi')) { file_p = 'video'; }
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount)
{
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null)
{
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name))
{
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
}
}
}
}
if (stoargearr.length == what.files.length) { waitfor(stoargearr); }
else { reader.readAsDataURL(what.files[oD]); }
}
}
}
Does the "File reader API" react different on audio files as it does on video or image files?
Thanks for any help.
here it goes.
for (var oD = 0; oD < what.files.length; oD++) {
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) {
return;
};
if (file_s.exec(file) && !what.multiple) {
pL = true;
} else {
if (what.files.length > what.filecount) {
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null) {
quest0.innerHTML = 'too many files added. only ' + what.filecount + ' are allowed.';
};
return;
};
pL = true;
if (!lastform.includes(what.form.id)) {
pL = false;
};
};
if (what.files && what.files[oD] && pL == true) {
if (file_prev != null) {
if (file_prev.getAttribute('data-src') == '') {
file_prev.setAttribute('data-src', file_prev.src);
};
file_prev.src = file_backsrc;
};
reader.onload = function(e) {
init();
if (typeof file_prev === 'undefined') {
if (quest1 != null) {
quest1.innerHTML = 'Error occoured';
};
return;
};
if (file_p == 'img' || file_p == 'video' || file_p == 'audio') {
file_prev.src = e.target.result;
};
if (file_p == 'canvas') { /*not yet*/ };
kill.classList.remove('invisible');
if (quest1 != null) {
quest1.innerHTML = 'file done';
};
};
reader.onerror = function(e) {
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
};
function waitfor(arr) {
if (arr == null || arr.length == 0) {
return;
};
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
};
if (what.multiple) {
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++) {
var oB = what.files[oD],
oB0, oB1;
if (oB.type.includes('im')) {
file_p = 'img';
};
if (oB.type.includes('au')) {
file_p = 'audio';
};
if (oB.type.includes('vi')) {
file_p = 'video';
};
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount) {
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null) {
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name)) {
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
};
};
};
};
if (stoargearr.length == what.files.length) {
waitfor(stoargearr);
};
} else {
reader.readAsDataURL(what.files[oD]);
};
};
};```
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
This block gives no output on audio files.
There is a print button in my page, where it opens a popup. If I choose the text, it prints it. But, if I press the print button, it prints 2 blank pages.
I tried printing other pages in the application, and they print normally. It's only the specific pop up that has the printing issue.
The code is typical, there are no errors in it:
ControlHandlers.GridPrint = function(iRecType, sIDs) {
setTimeout(function() {
try {
if (MenuFolders.AppMode == 2) {
$("#CalendarContainerDiv").printElement();
}
if (MenuFolders.AppMode == 3) {
$("#ActivitiesDiv").printElement();
}
if (MenuFolders.AppMode == 4) {
$("#ContactsDiv").printElement();
}
if (MenuFolders.AppMode == 5) {
if (mo_CustomPage == true) {
//PrintElem("ReportsContainerDiv");
$("#ReportsDivEmpty").printElement();
// window.print();
return;
}
if (!sIDs) {
sIDs = '';
}
if (!sIDs != '') {
var keys = BIGrid.getSelectedRowKeys();
if (keys.length > 0) {
for (i = 0; i < keys.length; i++) {
if (sIDs != '') {
sIDs = sIDs + ','
};
sIDs = sIDs + keys[i].toString();
}
} else {
ODCloseBusy();
ODAlert(ODGetMsg(2368));
return;
}
}
if (iRecType == 1) {
var query = {
iObjectID: BIObjectID,
iRecType: 1,
sIDs: sIDs
};
ODShowBusyWindow();
FileWindow = true;
//ShowReport("Download.html?v=2");
//if (app.isMobileView()) {
// FileWindow = window.open("Download.html?v=2", "_blank");
//} else {
// var sParams = "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,width=" + Math.round(screen.width / 1.5) + ", height=" + Math.round(screen.height / 1.5) + ", top=" + ((screen.height / 2) - (screen.height / 1.5 / 2)) + ", left=" + ((screen.width / 2) - (screen.width / 1.5 / 2));
// FileWindow = window.open("Download.html?v=3", ODGetMsg(27), sParams);
//}
$.ajax({
type: "POST",
url: "WebMethods.aspx/WaitProcess",
//headers: { "Accept-Encoding": "gzip" },
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(result) {
var sData;
sData = eval('(' + result.d + ')');
if (sData.err != "") {
ODAlertError(sData.err);
ODCloseBusy();
return;
}
DownloadFile(sData.data, "-1", "");
ODCloseBusy();
},
failure: function(msg) {
ODCloseBusy();
ODAlertError(msg);
},
error: function(a, b, c) {
ODCloseBusy();
ODAlertError(c + ' - ' + a.responseText);
}
});
return;
}; //EKTYPWSH LISTAS
if (BIGridPrintField != '') {
if (BIForcePrintFile != '') {
DownloadFile(BIForcePrintFile, "-1", "");
BIForcePrintFile = "";
return;
}
if (BIData && (BIData[BIGridPrintField] == '' || !BIData[BIGridPrintField])) {
ODAlertError(ODGetMsg(12061));
} else {
var FilesToPrint = '';
var selectedRowsData = BIGrid.getSelectedRowsData();
for (i = 0; i < selectedRowsData.length; i++) {
if (FilesToPrint != '') {
FilesToPrint = FilesToPrint + '|'
};
if (selectedRowsData[i][BIGridPrintField] != '') {
FilesToPrint = FilesToPrint + selectedRowsData[i][BIGridPrintField];
}
}
//BIData[BIGridPrintField]
DownloadFile(FilesToPrint, "-1", "");
}
} else {
$("#ReportsDiv").printElement();
}
}
} catch (e) {
ControlHandlers.ODAlertError(e);
}
I have an array that contains some data. Each block of data is separated by an empty line, and the size of the block varies. How would I go about checking each block to see if it contained the values I need. Here is my current code that handles this. (This doesn't work because it will always check 7 lines)
input = ["ecl:gry pid:860033327 eyr:2020 hcl:#fffffd",
"byr:1937 iyr:2017 cid:147 hgt:183cm",
"",
"iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884",
"hcl:#cfa07d byr:1929",
"",
"hcl:#ae17e1 iyr:2013",
"eyr:2024",
"ecl:brn pid:760753108 byr:1931",
"hgt:179cm",
"",
"hcl:#cfa07d eyr:2025 pid:166559648",
"iyr:2011 ecl:brn hgt:59in"];
var byr = false;
var iyr = false;
var eyr = false;
var hgt = false;
var hcl = false;
var ecl = false;
var pid = false;
var numberOfLines = 1;
if (input[arrayIndex+1].charAt(0) == ""){
numberOfLines = 1;
} else if (input[arrayIndex+2].charAt(0) == ""){
numberOfLines = 2;
} else if (input[arrayIndex+3].charAt(0) == ""){
numberOfLines = 3;
} else if (input[arrayIndex+3].charAt(0) == ""){
numberOfLines = 3;
} else if (input[arrayIndex+4].charAt(0) == ""){
numberOfLines = 4;
} else if (input[arrayIndex+5].charAt(0) == ""){
numberOfLines = 5;
} else if (input[arrayIndex+6].charAt(0) == ""){
numberOfLines = 6;
}
else if (input[arrayIndex+7].charAt(0) == ""){
numberOfLines = 7;
}
if (input[arrayIndex].includes("byr:") || input[arrayIndex + 1].includes("byr:") || input[arrayIndex + 2].includes("byr:") || input[arrayIndex + 3].includes("byr:") || input[arrayIndex + 4].includes("byr:") || input[arrayIndex + 5].includes("byr:") || input[arrayIndex + 6].includes("byr:")) {
byr = true;
} else { byr = false; }
if (input[arrayIndex].includes("iyr") || input[arrayIndex + 1].includes("iyr:") || input[arrayIndex + 2].includes("iyr:") || input[arrayIndex + 3].includes("iyr:") || input[arrayIndex + 4].includes("iyr:") || input[arrayIndex + 5].includes("iyr:") || input[arrayIndex + 6].includes("iyr:")) {
iyr = true;
} else { iyr = false; }
if (input[arrayIndex].includes("eyr:") || input[arrayIndex + 1].includes("eyr:") || input[arrayIndex + 2].includes("eyr:") || input[arrayIndex + 3].includes("eyr:") || input[arrayIndex + 4].includes("eyr:") || input[arrayIndex + 5].includes("eyr:") || input[arrayIndex + 6].includes("eyr:")) {
eyr = true;
} else { eyr = false; }
if (input[arrayIndex].includes("hgt:") || input[arrayIndex + 1].includes("hgt:") || input[arrayIndex + 2].includes("hgt:") || input[arrayIndex + 3].includes("hgt:") || input[arrayIndex + 4].includes("hgt:") || input[arrayIndex + 5].includes("hgt:") || input[arrayIndex + 6].includes("hgt:")) {
hgt = true;
} else { hgt = false; }
if (input[arrayIndex].includes("hcl:") || input[arrayIndex + 1].includes("hcl:") || input[arrayIndex + 2].includes("hcl:") || input[arrayIndex + 3].includes("hcl:") || input[arrayIndex + 4].includes("hcl:") || input[arrayIndex + 5].includes("hcl:") || input[arrayIndex + 6].includes("hcl:")) {
hcl = true;
} else { hcl = false; }
if (input[arrayIndex].includes("ecl:") || input[arrayIndex + 1].includes("ecl:") || input[arrayIndex + 2].includes("ecl:") || input[arrayIndex + 3].includes("ecl:") || input[arrayIndex + 4].includes("ecl:") || input[arrayIndex + 5].includes("ecl:") || input[arrayIndex + 6].includes("ecl:")) {
ecl = true;
} else { ecl = false; }
if (input[arrayIndex].includes("pid:") || input[arrayIndex + 1].includes("pid:") || input[arrayIndex + 2].includes("pid:") || input[arrayIndex + 3].includes("pid:") || input[arrayIndex + 4].includes("pid:") || input[arrayIndex + 5].includes("pid:") || input[arrayIndex + 6].includes("pid:")) {
pid = true;
} else { pid = false; }
if (byr && iyr && eyr && hgt && hcl && ecl && pid) {
console.log("True");
} else {
console.log("False");
}
Using reduce to create an object with all your fields might be easier:
const inputStr = `ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in`;
const input = inputStr.split('\n\n'); // Split on empty lines
const fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'];
input.forEach(passport => {
const res = fields.reduce((res, field) => ({
...res, // Keep the previous fields
[field]: passport.includes(field) // Add the current one
}), {});
console.log(JSON.stringify(res)); // {"byr": true, "iyr": true, ...}
const allFieldsArePresent = Object.values(res).every(val => val);
console.log(allFieldsArePresent);
});
When writing code, always try to think "DRY" (Don't Repeat Yourself). If you find yourself repeating things over and over, it's a big code-smell, there is a 99.999% chance it could be written in a shorter, more maintainable way.
I'm getting on chrome Uncaught SyntexError: Unexpected end of input in the first line of code I went through my code but I cannot find it please help me.
I searched through treads here but noting.
What do I need to do in order to fix it?
<%--JS--%>
<script type="text/javascript">
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
$(document).ready(function () {
try {
if (is_chrome) {
//alert("is chrome!!");
$("span#spanAddPerson").css("top", "0px");
}
} catch (err) {
alert(err);
}
});
</script>
<script type="text/javascript">
function setClientTime(sender, eventArgs) {
try {
var datePicker = $find("<%= actOverViewDateTime.ClientID %>");
var date = datePicker.get_selectedDate();
if (date == null) {
var nowDate = new Date();
datePicker.set_selectedDate(nowDate);
}
} catch (err) {
alert(err);
}
}
function StatusCheck(sender, args) {
var status = $find("<%= rcbStatus.ClientID %>");
var datePickerEndingTime = $find("<%= rdtpEndingTime.ClientID %>");
var item = status.get_text();
if (item == "Closed") {
document.getElementById('EndingTime').style.visibility = 'visible'
datePickerEndingTime.set_visible(true);
var nowDate = new Date();
datePickerEndingTime.set_selectedDate(nowDate)
datePickerEndingTime.set_maxDate(nowDate);
} else {
document.getElementById('EndingTime').style.visibility = 'hidden'
datePickerEndingTime.set_visible(false);
}
}
//IE7 bug
// Only Numeric keys and "."-(46) are allowed
function isNumberKey(e, allowDecimalPoint) {
var key = e.charCode || e.keyCode || 0;
var keychar = String.fromCharCode(key);
if (!allowDecimalPoint && key == 46) e.preventDefault();
if (((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode == 0) /* backspace, end, begin, top, bottom, right, left, del, tab */
|| (key >= 46 && key <= 57)) { /* 0-9 */
return;
} else {
e.preventDefault();
}
}
function abc(sender) {
var radTextBox1 = $find("actOverViewCode");
radTextBox1.get_styles().EnabledStyle[0] = "background-color: LightYellow;";
radTextBox1.updateCssClass();
}
function NumbersOnly(sender, args) {
var keycode = args.get_keyCode()
if (keycode == 8) {
//Checking if the key pressed is BackSpace key, then do not cancel the event.
return;
}
if (keycode != 46 && keycode != 45 && keycode > 31 && (keycode < 48 || keycode > 57)) {
args.set_cancel(true);
}
}
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
var month = '0' + month;
}
if (day.toString().length == 1) {
var day = '0' + day;
}
if (hour.toString().length == 1) {
var hour = '0' + hour;
}
if (minute.toString().length == 1) {
var minute = '0' + minute;
}
if (second.toString().length == 1) {
var second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
}
function checkLevelZone(sender, args) {
var txtOffSite = $find("<%=txtOffSite.ClientID %>");
var checkbox = $find("<%=cbIsOffSite.ClientID %>");
var level = $find("<%=ActOverviewLevel.ClientID %>");
var zone = $find("<%=ActOverViewZone.ClientID %>");
if (checkbox.get_checked()) {
level.clearSelection();
zone.clearSelection();
level.trackChanges();
zone.trackChanges();
level.disable();
zone.disable();
txtOffSite.enable();
} else {
level.enable();
//zone.enable();
txtOffSite.disable();
}
}
function CheckPersonLocation(sender, args) {
var l_location = $find("<%=rcbPeopleLocation.ClientID %>");
var count = l_location.get_checkedItems().length;
if (count <= 1) {
radconfirm('Would you like to add more location to that person?</br>', confirmDisableCallBackFn, 370, 200, null, 'Case Global Alert');
} else {
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
}
function confirmDisableCallBackFn(arg) {
if (arg == true) {
check.set_checked(false);
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
else {
check.set_checked(true);
}
}
function togglePopupModality() {
var wnd = $find("<%=modalPopup.ClientID %>");
wnd.set_modal(!wnd.get_modal());
if (!wnd.get_modal()) document.documentElement.focus();
}
function showDialogInitially() {
var wnd = $find("<%=modalPopup.ClientID %>");
wnd.show();
Sys.Application.remove_load(showDialogInitially);
}
function disableSubmitButton(sender, eventArgs) {
$find("<%=btnAddActivity.ClientID %>").set_enabled(false);
__doPostBack("<%=btnAddActivity.UniqueID %>", "");
}
function confirmPersonDuplicateCallBackFn(arg) {
if (arg == true) {
$get("<%=hfCheckDuplicate.ClientID %>").value = "0";
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
}
function DisableSaving(sender, args) {
var isValid = Page_ClientValidate('validationOverviewTab');
if (isValid) {
var rcbStatus = $find("<%=rcbStatus.ClientID %>");
if (rcbStatus.get_text() == "Open") {
sender.set_autoPostBack(true);
} else {
var OverViewDateTime = $find("<%=actOverViewDateTime.ClientID %>");
var getOverViewDateTime = OverViewDateTime.get_selectedDate();
var date = new Date(getOverViewDateTime), mnth = ("0" + (date.getMonth() + 1)).slice(-2), day = ("0" + date.getDate()).slice(-2);
var resultOverViewDate = [mnth, day, date.getFullYear()].join("-");
var getOverViewHours = getOverViewDateTime.getHours();
var getOverViewMin = getOverViewDateTime.getMinutes();
var EndingDateTime = $find("<%=rdtpEndingTime.ClientID %>");
var getEndingDateTime = EndingDateTime.get_selectedDate();
var EndDate = new Date(getEndingDateTime), mnth = ("0" + (getEndingDateTime.getMonth() + 1)).slice(-2), day = ("0" + getEndingDateTime.getDate()).slice(-2);
var resultEndingDate = [mnth, day, date.getFullYear()].join("-");
var getEndingHours = getEndingDateTime.getHours();
var getEndingMin = getEndingDateTime.getMinutes();
//Check for Valid Dates
if (resultOverViewDate > resultEndingDate) {
radalert("Date/Time is greater than Ending Time Please correct date and time<h3 style='color: #ff0000;'></h3>", 380, 170, "Alert");
} else if (resultOverViewDate < resultEndingDate) {
sender.set_autoPostBack(true);
}
if (resultOverViewDate == resultEndingDate) {
//Check if it's the case of equal hours
if (getOverViewHours == getEndingHours) {
if (getOverViewMin > getEndingMin) {
radalert("Date/Time-minutes must be less then Ending Time-minutes<h3 style='color: #ff0000;'></h3>", 380, 170, "Alert");
} else if (getOverViewHours == getEndingHours && getOverViewMin == getEndingMin) {
sender.set_autoPostBack(true);
}
else {
sender.set_autoPostBack(true);
}
} else {
sender.set_autoPostBack(true);
}
}
}
}
}
function SaveStatus(sender, args) {
var status = $find("<%= rcbStatus.ClientID %>");
var datePickerEndingTime = $find("<%= rdtpEndingTime.ClientID %>");
var item = status.get_text();
if (item == "Closed") {
document.getElementById('EndingTime').style.visibility = 'visible'
datePickerEndingTime.set_visible(true);
} else {
document.getElementById('EndingTime').style.visibility = 'hidden'
datePickerEndingTime.set_visible(false);
}
}
Try to declare is_chrome in try block and end your script tag,
<script type="text/javascript">
$(document).ready(function () {
try {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
//alert("is chrome!!");
$("span#spanAddPerson").css({'top': "0px"});//top syntax is like this.
}
} catch (err) {
alert(err);
}
});
</script>
<script type="text/javascript">
function setClientTime(sender, eventArgs) {
try {
var datePicker = $find("<%= actOverViewDateTime.ClientID %>");
var date = datePicker.get_selectedDate();
if (date == null) {
var nowDate = new Date();
datePicker.set_selectedDate(nowDate);
}
} catch (err) {
alert(err);
}
}
function StatusCheck(sender, args) {
var status = $find("<%= rcbStatus.ClientID %>");
var datePickerEndingTime = $find("<%= rdtpEndingTime.ClientID %>");
var item = status.get_text();
if (item == "Closed") {
document.getElementById('EndingTime').style.visibility = 'visible'
datePickerEndingTime.set_visible(true);
var nowDate = new Date();
datePickerEndingTime.set_selectedDate(nowDate)
datePickerEndingTime.set_maxDate(nowDate);
} else {
document.getElementById('EndingTime').style.visibility = 'hidden'
datePickerEndingTime.set_visible(false);
}
}
//IE7 bug
// Only Numeric keys and "."-(46) are allowed
function isNumberKey(e, allowDecimalPoint) {
var key = e.charCode || e.keyCode || 0;
var keychar = String.fromCharCode(key);
if (!allowDecimalPoint && key == 46) e.preventDefault();
if (((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode == 0) /* backspace, end, begin, top, bottom, right, left, del, tab */
|| (key >= 46 && key <= 57)) { /* 0-9 */
return;
} else {
e.preventDefault();
}
}
function abc(sender) {
var radTextBox1 = $find("actOverViewCode");
radTextBox1.get_styles().EnabledStyle[0] = "background-color: LightYellow;";
radTextBox1.updateCssClass();
}
function NumbersOnly(sender, args) {
var keycode = args.get_keyCode()
if (keycode == 8) {
//Checking if the key pressed is BackSpace key, then do not cancel the event.
return;
}
if (keycode != 46 && keycode != 45 && keycode > 31 && (keycode < 48 || keycode > 57)) {
args.set_cancel(true);
}
}
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
var month = '0' + month;
}
if (day.toString().length == 1) {
var day = '0' + day;
}
if (hour.toString().length == 1) {
var hour = '0' + hour;
}
if (minute.toString().length == 1) {
var minute = '0' + minute;
}
if (second.toString().length == 1) {
var second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
}
function checkLevelZone(sender, args) {
var txtOffSite = $find("<%=txtOffSite.ClientID %>");
var checkbox = $find("<%=cbIsOffSite.ClientID %>");
var level = $find("<%=ActOverviewLevel.ClientID %>");
var zone = $find("<%=ActOverViewZone.ClientID %>");
if (checkbox.get_checked()) {
level.clearSelection();
zone.clearSelection();
level.trackChanges();
zone.trackChanges();
level.disable();
zone.disable();
txtOffSite.enable();
} else {
level.enable();
//zone.enable();
txtOffSite.disable();
}
}
function CheckPersonLocation(sender, args) {
var l_location = $find("<%=rcbPeopleLocation.ClientID %>");
var count = l_location.get_checkedItems().length;
if (count <= 1) {
radconfirm('Would you like to add more location to that person?</br>', confirmDisableCallBackFn, 370, 200, null, 'Case Global Alert');
} else {
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
}
function confirmDisableCallBackFn(arg) {
if (arg == true) {
check.set_checked(false);
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
else {
check.set_checked(true);
}
}
function togglePopupModality() {
var wnd = $find("<%=modalPopup.ClientID %>");
wnd.set_modal(!wnd.get_modal());
if (!wnd.get_modal()) document.documentElement.focus();
}
function showDialogInitially() {
var wnd = $find("<%=modalPopup.ClientID %>");
wnd.show();
Sys.Application.remove_load(showDialogInitially);
}
function disableSubmitButton(sender, eventArgs) {
$find("<%=btnAddActivity.ClientID %>").set_enabled(false);
__doPostBack("<%=btnAddActivity.UniqueID %>", "");
}
function confirmPersonDuplicateCallBackFn(arg) {
if (arg == true) {
$get("<%=hfCheckDuplicate.ClientID %>").value = "0";
__doPostBack("<%=btnAddPerson.UniqueID %>", "");
}
}
function DisableSaving(sender, args) {
var isValid = Page_ClientValidate('validationOverviewTab');
if (isValid) {
var rcbStatus = $find("<%=rcbStatus.ClientID %>");
if (rcbStatus.get_text() == "Open") {
sender.set_autoPostBack(true);
} else {
var OverViewDateTime = $find("<%=actOverViewDateTime.ClientID %>");
var getOverViewDateTime = OverViewDateTime.get_selectedDate();
var date = new Date(getOverViewDateTime), mnth = ("0" + (date.getMonth() + 1)).slice(-2), day = ("0" + date.getDate()).slice(-2);
var resultOverViewDate = [mnth, day, date.getFullYear()].join("-");
var getOverViewHours = getOverViewDateTime.getHours();
var getOverViewMin = getOverViewDateTime.getMinutes();
var EndingDateTime = $find("<%=rdtpEndingTime.ClientID %>");
var getEndingDateTime = EndingDateTime.get_selectedDate();
var EndDate = new Date(getEndingDateTime), mnth = ("0" + (getEndingDateTime.getMonth() + 1)).slice(-2), day = ("0" + getEndingDateTime.getDate()).slice(-2);
var resultEndingDate = [mnth, day, date.getFullYear()].join("-");
var getEndingHours = getEndingDateTime.getHours();
var getEndingMin = getEndingDateTime.getMinutes();
//Check for Valid Dates
if (resultOverViewDate > resultEndingDate) {
radalert("Date/Time is greater than Ending Time Please correct date and time<h3 style='color: #ff0000;'></h3>", 380, 170, "Alert");
} else if (resultOverViewDate < resultEndingDate) {
sender.set_autoPostBack(true);
}
if (resultOverViewDate == resultEndingDate) {
//Check if it's the case of equal hours
if (getOverViewHours == getEndingHours) {
if (getOverViewMin > getEndingMin) {
radalert("Date/Time-minutes must be less then Ending Time-minutes<h3 style='color: #ff0000;'></h3>", 380, 170, "Alert");
} else if (getOverViewHours == getEndingHours && getOverViewMin == getEndingMin) {
sender.set_autoPostBack(true);
}
else {
sender.set_autoPostBack(true);
}
} else {
sender.set_autoPostBack(true);
}
}
}
}
}
function SaveStatus(sender, args) {
var status = $find("<%= rcbStatus.ClientID %>");
var datePickerEndingTime = $find("<%= rdtpEndingTime.ClientID %>");
var item = status.get_text();
if (item == "Closed") {
document.getElementById('EndingTime').style.visibility = 'visible'
datePickerEndingTime.set_visible(true);
} else {
document.getElementById('EndingTime').style.visibility = 'hidden'
datePickerEndingTime.set_visible(false);
}
}
</script>
I have some javascript code like below
function mask(eventVal,val){
var len = val.value.length;
var key = whichKey(eventVal);
if(key>47 && key<58)
{
if( len==0 )val.value=val.value+'('
else if( len==4 )val.value=val.value+') '
else if(len==9 )val.value=val.value+'-'
else val.value=val.value;
}
else{
val.value = val.value.replace(/[^0-9-]/,'')
val.value = val.value.replace('--','-')
}
}
function whichKey(eventVal) {
var code;
if (!eventVal) var eventVal = window.event;
if (eventVal.keyCode) code = eventVal.keyCode;
else if (eventVal.which) code = eventVal.which;
return code;
}
HTML
<input type="text" name="PhoneNumber" id="PhoneNumber" value="" onkeydown="mask(event,this)"/>
It is working fine when I am typing phone number like 1234567890 is automatically converting into (123) 456-7890 when I am trying to remove value like remove 0 from the end then formatting is getting ruined completely. like 123) 456-789 and even it is getting ruined when I am click any other place. Can Any one help me to fix it?
check this script..
<script language="javascript">
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 14;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object){
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object){
phonevalue2 = ParseChar(object.value, zChar);
}
function up(object,e) {
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber1(object)
if(keycode >= 48){
ValidatePhone(object)
}
}
function down(object,e) {
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber2(object)
}
function GetCursorPosition(){
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i=0; i<t1.length; i++)
{
if (t1.substring(i,1) != t2.substring(i,1)) {
if(!bool) {
cursorposition=i
window.status=cursorposition
bool=true
}
}
}
}
function ValidatePhone(object){
var p = phonevalue1
p = p.replace(/[^\d]*/gi,"")
if (p.length < 3) {
object.value=p
} else if(p.length==3){
pp=p;
d4=p.indexOf('(')
d5=p.indexOf(')')
if(d4==-1){
pp="("+pp;
}
if(d5==-1){
pp=pp+")";
}
object.value = pp;
} else if(p.length>3 && p.length < 7){
p ="(" + p;
l30=p.length;
p30=p.substring(0,4);
p30=p30+") "
p31=p.substring(4,l30);
pp=p30+p31;
object.value = pp;
} else if(p.length >= 7){
p ="(" + p;
l30=p.length;
p30=p.substring(0,4);
p30=p30+") "
p31=p.substring(4,l30);
pp=p30+p31;
l40 = pp.length;
p40 = pp.substring(0,9);
p40 = p40 + "-"
p41 = pp.substring(9,l40);
ppp = p40 + p41;
object.value = ppp.substring(0, maxphonelength);
}
GetCursorPosition()
if(cursorposition >= 0){
if (cursorposition == 0) {
cursorposition = 2
} else if (cursorposition <= 2) {
cursorposition = cursorposition + 1
} else if (cursorposition <= 4) {
cursorposition = cursorposition + 3
} else if (cursorposition == 5) {
cursorposition = cursorposition + 3
} else if (cursorposition == 6) {
cursorposition = cursorposition + 3
} else if (cursorposition == 7) {
cursorposition = cursorposition + 4
} else if (cursorposition == 8) {
cursorposition = cursorposition + 4
e1=object.value.indexOf(')')
e2=object.value.indexOf('-')
if (e1>-1 && e2>-1){
if (e2-e1 == 4) {
cursorposition = cursorposition - 1
}
}
} else if (cursorposition == 9) {
cursorposition = cursorposition + 4
} else if (cursorposition < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition == 12) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 13) {
cursorposition = cursorposition
}
var txtRange = object.createTextRange();
txtRange.moveStart( "character", cursorposition);
txtRange.moveEnd( "character", cursorposition - object.value.length);
txtRange.select();
}
}
function ParseChar(sStr, sChar)
{
if (sChar.length == null)
{
zChar = new Array(sChar);
}
else zChar = sChar;
for (i=0; i<zChar.length; i++)
{
sNewStr = "";
var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);
while (iEnd != -1)
{
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
sStr = sNewStr;
}
return sNewStr;
}
</script>
HTML:
<input type="text" name="txtInput" onkeydown="javascript:down(this,event);" onkeyup="javascript:up(this,event);">
You can try this code to replace your last digit
<script type="text/javascript">
function fnc()
{
str=document.getElementById("atext").value;
x=(str.match(pattern));
if(x!="")
{str=str.replace(/[0-9]$/g,'')}
alert(str);
}
</script>
<body>
<input type="text" id="atext">
<input type="button" onClick="fnc()">
</body>