How to insert something in textarea at the location indicated by the mouse - javascript

I created a script that inserts emojis inside a textarea. The problem is that I use innerHTML to insert the emoji and that way it only inserts at the beginning or end of the content of the textarea. I would like to be able to insert this in any location indicated by the user so that if you have already written what you want you can return to a certain part of the text and simply insert your emoji. Does anyone know how to help me?

Sorry it's not really pretty but I feel like this example has everthing to explain it, you can save the snippet in an html page, load it and examine the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insertion test</title>
<style>
.classic-button {
width: 140px;
height: 60px;
font-weight: bold;
font-size: 20px;
border: 4px solid black;
background-color: lightgray;
}
table {
border-collapse: collapse;
}
td {
border: 4px solid black;
}
.fs-24-b {
font-size: 24px;
font-weight: bold;
}
.fs-32-b {
font-size: 32px;
font-weight: bold;
}
.tBoxFill {
width: 100%;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
font-size: 32px;
}
.td-button {
padding: 20px;
}
</style>
<script>
let insertIn = (str1, str2, at) => {
return str1.slice(0,at) + str2 + str1.slice(at);
}
function doGetCaretPosition (oField) {
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
function getprintLastPost() {
document.getElementById('printLastPost')
.innerText = 'Last position : '
+ doGetCaretPosition(document.getElementById('TBtoFill'));
}
function insertInTBox(tBoxDOM, text) {
let insStr = text;
let oldCaretPos = doGetCaretPosition(tBoxDOM);
let newCaretPos = oldCaretPos + insStr.length;
tBoxDOM.value = insertIn(tBoxDOM.value, insStr, oldCaretPos);
tBoxDOM.selectionEnd = newCaretPos;
}
function insertStuff() {
let toBox = document.getElementById("TBtoFill");
let inBox = document.getElementById("TBtoInsert");
insertInTBox(toBox, inBox.value);
}
</script>
</head>
<body>
<center>
<table>
<tr>
<td colspan="5">
<textarea class="fs-24-b" id="TBtoFill" cols="70" rows="10">
</textarea>
</td>
</tr>
<tr>
<td colspan="5" class="td-button">
<button class="classic-button" onclick="getprintLastPost()">
Get last pos
</button>
<span class="fs-32-b"> :
</span>
<span id="printLastPost" class="fs-32-b">Last position : ?</span>
</td>
</tr>
<tr>
<td colspan="1" class="td-button">
<button class="classic-button" onclick="insertStuff()">
Insert
</button>
<span class="fs-32-b"> : </span>
</td>
<td style="width: 80%">
<textarea class="tBoxFill fs-32-b" id="TBtoInsert"></textarea>
</td>
</tr>
</table>
</center>
</body>
</html>
Basically, you just take the utf8 or unicode value of the emoji and then you keep the function doGetCaretPosition() to use insertInTBox(). You slice the textbox string in two based on the last position of the caret which the function will tell you, then concatenate left-part->emoji->right part.

Related

Can't get the numeric value from HTML using parseInt or Number in my js function

So I'm trying to complete this simple html page for a friend's project, the goal is to get 2 user entries, minutes and seconds, that will be compared to the data already in the table and if the minutes and seconds entered are greater than one of the time in the table, it will be replaced by the entry.
I've never worked with js except to make some simple prompt or alert so I don't know what I'm supposed to do.
Here is the html, js and css :
function timeEntry() {
var min1 = Number(document.getElementById('firstTimeMin'));
var sec1 = Number(document.getElementById('firstTimeSec'));
var min2 = Number(document.getElementById('secondTimeMin'));
var sec2 = Number(document.getElementById('secondTimeSec'));
var min3 = Number(document.getElementById('thirdTimeMin'));
var sec3 = Number(document.getElementById('thirdTimeSec'));
var entryMin = Number(prompt('What is the time in minutes ?'));
var newTimeMin = entryMin;
var entrySec = Number(prompt('What is the time in seconds'));
var newTimeSec = entrySec;
for (var i = 0; i < 3; i++) {
if (entryMin > min1 && entrySec > sec1) {
document.getElementById('firstTimeMin').innerHTML = newTimeMin;
document.getElementById('firstTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min2 && entrySec > sec2) {
document.getElementById('secondTimeMin').innerHTML = newTimeMin;
document.getElementById('secondTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min3 && entrySec > sec3) {
document.getElementById('thirdTimeMin').innerHTML = newTimeMin;
document.getElementById('thirdTimeSec').innerHTML = newTimeSec;
break;
}
};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
section {
width: 100%;
height: 100%;
}
table,
td {
width: 40%;
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
button {
cursor: pointer;
font-weight: 700;
}
<!DOCTYPE html>
<html>
<head>
<title>Table of best times</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="javascript/besttime.js"></script>
</head>
<body>
<section>
<table>
<tbody>
<caption>The best times</caption>
<tr>
<td id="firstTimeMin">1</td>
<td id="firstTimeSec">2</td>
</tr>
<tr>
<td id="secondTimeMin">3</td>
<td id="secondTimeSec">4</td>
</tr>
<tr>
<td id="thirdTimeMin">5</td>
<td id="thirdTimeSec">6</td>
</tr>
</tbody>
</table>
<button onclick="timeEntry()">
Enter a new time
</button>
</section>
</body>
</html>
My idea was to simply get the data already in the table using Number or parseInt to get the number value, but either way from the test I've been doing, when I try to get the element from html, it tells me that I get a number type but when I try to use it in an operation it returns NaN. Maybe I'm just stupid, but I've been reading and looking for a day for a way to get the data from the cells as numbers, but aside from Number or parseInt or using a form, I haven't seen a way to do this and it feels like the more I search the less I understand why it doesn't work.
Any help or clue on how to get this done, even it means start back from scratch would be really appreciated.
document.getElementById('firstTimeMin') only get the DOM Element, you should do document.getElementById('firstTimeMin').innerHTML to get the content of the HTML so you'll be able to get the number using parseInt() or Number.
Do the same with every elements.

Modal pops up after Ajax call completes instead of before or during

I am trying to get a modal popup to show "Please Wait" while an Ajax call is being made. The pop up occurs only after the call completes.
When I click my web link, everything is working, except the modal popup that is supposed to say "Please Wait" flashes for a split second AFTER the delay that the user is supposed to be asked to wait thru. That is, the modal pops up AFTER the Ajax call is completed instead of before.
When the page loads, it calls AjaxInitialUpdate. This works fine.
The issue is when you click the button that calls AjaxChangePassword.
The function is supposed to pull up a modal, then contact the web server, before finally removing the model and calling the AjaxInitialUpdate function to refresh the whole screen.
The issue is that the AjaxChangePassword modal doesn't pop up until the web query completes (by which time, there is no point in telling the user -- Please Wait).
Now, I am totally self-taught here, so I may be calling things by the wrong name or terms. I welcome any ideas to make it run better, but please be detailed, I'm still very novice in Java.
Also, the last time I did any kind of HTML programming was before Style sheets were the way to go, so I'm kind of having to learn them as well (and refresh on all the rest, so please explain any answer in detail).
Lastly, the server side of this is written in Powershell and is single threaded so I am trying to put as much in the HTML file as possible instead of calling secondary files, like style sheets and images.
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
/* Believe these are not needed.
Imported from web site that I copied the code from.
padding: 8px 8px;
outline: none;
border: none;
border-radius: 115px;
box-shadow: 0 3px #999; */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 70%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
#IndividualSystem td, #IndividualSystem th {
text-align: left;
padding: 8px;
color: black
border: 1px solid black;
}
#IndividualSystem tr {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #eeeeee;
}
.tab { margin-left: 40px; }
.button {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
.button2 {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #000080;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button2:hover {background-color: #df330e}
.button2:active {
background-color: #FD2E02;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
</style>
<Title>Cyber Track</title>
</head>
<body>
<table>
<tr>
<td>blah</td>
<td><h1>Systems and Passwords</H1>
<h3>Information within this page is considered confidential.</h3>
</td></tr>
</table>
<hr>
<input type="hidden" id="Leftlink" name="Leftlink" value="0">
<input type="hidden" id="Rightlink" name="Rightlink" value="0">
<input type="hidden" id="serverID" name="serverID" value="server8\admin-server8">
<input type="hidden" id="count" name="count" value="10"> <!--- Number of servers per page on server list //-->
<!-- The Modals #1 -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h4><label id="ModalTextLine1">Loading content from server</label></h4>
</div>
</div>
<!-- The Modals #2 -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close2">×</span>
How long do you need the password?
<form action='#'>
<select name="days">
<option value='1' >1 day or less</option>
<option value='7'>between 1 and 2 days</option>
<option value='7'>between 2 and 7 days</option>
<option value='30'>between 7 and 30 days</option>
<option value='365' selected>for up to a year.</option>
</select>
<br>
<input type="submit" value="Process Request">
</form>
</div>
</div>
<script>
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close2")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it (or actually, just hide it)
window.onclick = function(event) {
if (modal2.style.display != "none")
{
if (event.target == modal2) {
modal2.style.display = "none";
}
}
}
</script>
<!-- End Loaded from function -->
<table id="IndividualSystem"> <!-- IndividualSystem - to define needed style sheet //-->
<tr>
<td style="width: 215px;">Server</td>
<td style="width: 259px;"><label ID="DynServerName">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">User ID</td>
<td style="width: 259px;"><label ID="DynAdminID">Loading</label></td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td style="width: 215px;">Checked out status:</td>
<td style="width: 259px;"><label ID="DynLastCheckedout">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;" valign='top' >Last checked out by:</td>
<td style="width: 259px;" valign='top' ><label ID="DynLastCheckedBy">Loading...</label>
<button class="button" onclick="javascript:AjaxCheckOutPassword()" id="PassStatus">Loading</button> <!-- AjaxCheckOutPassword -->
</td>
</tr>
<tr>
<td valign='top' style="width: 215px;">Expected Check In Date:</td>
<td valign='top' style="width: 259px;"><label ID="DynExpectedBack">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">Date of last password change:</td>
<td style="width: 259px;"><label id="DynLastReset">Loading</label> <button class="button2" onclick="AjaxChangePassword()">Force Change Now!</button>
</td>
</tr>
<tr>
<th colspan="2">Notify:<br>
<table border="1" padding = "0" width=100%>
<tr>
<td width=200>On Use:</td><td><label id="DynEmailCheckOut">Loading</label></td>
</tr>
<tr>
<td width=200>On Checkin:</td><td><label id="DynEmailCheckIn">Loading</label></td>
</tr>
</table>
</th>
</tr>
<tr><td colspan="2">
<label ID="DynAccountPurpose"></label>
</td></tr>
</tbody>
</table>
<!-- Page Footer (if any) //-->
<!-- Page links left/up/right //-->
<table>
<tr><td width = 50>
<label id="Show-Left">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(-1)" text='Prior Server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9+Wwp/wDrVzHxS+Kmk/B3wfda3rdz9lsbPZ5kvlvJ951QfKis3V1HA7074ofE/SPhD4RvNc1m5+x6fZ7PNl8t5Nu50ReFBJyzgcDv6Dj853k8Zf8ABW/4sgY/sv4d6T0X9zPjzIfX9xNzPae/X+6Ob9naPtJ7GXM5Plgfod8H/jHoXxw8FW3iDw7c/btPvt4WTy5I87JHj6SKp+8jfwj8etddvHp+hrm/hb8L9H+EnhO30PQ7f7JZWe7am93xvdnPLsx6sT1P8q6QcDjbjt8prGPdm0rHjv7Yf7JOj/tW/DuTS9Q/0e6jx5M+Hfyv3sTt8qyIDkRAc9O1fH/7GP7T+t/sN+P4/hD8TB5OnQ5+yXX7t/s+Y5rt/kt45C2WmiHMnGeOMgfpEWJb73H0614v+2N+x1oP7WfgiTT9SBt7+HBtrr94/lZkhZvkWRAciEDn8OldCqc0fZzMJU+WXNA9hsb9NQtVlhfdG2drYIzg4PWp8r/drzb9lv4I3fwH+EWn+HNQ1X+2JrPzM3H2YW+7dNLJ90MwGBIB949Pwr0kx8/d/SsIO2jOjRn/2Q==' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
<td>
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(0)" text='Next server'>Return to main list</a>
</td>
<td width = "50">
<label id="Show-Right">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(1)" text='Next server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD97dc1U6Zp000cfnPHt+Tdt3ZIHX8a+Z/2Sv8AgpDpfx98c3/hjWNP/wCEf16Dy/Kt/Pe78zMcsp+ZYVQYSMHk/wAXqK+oihPT8DXx7/wUM/4J8r8Wo4/GXg5fsfi7T85XPmfat/2eH/lrMsabYkf+E5z64NEHGM+WezFUTcbw3PsMgtjj6nNO8pfSvjn/AIJv/wDBRD/hoLTj4b8UDyPFFr99s7vtG43Eg4jhWNdsca9+frmvsPa3/PX/AMdrSdKUHZkQqxmtCPULyK1tXef5YVxuPJ7+3PWvzt/a4/a28S/tm/Ek/Cz4V/vrOX/j7u/3S+ZiKK6T5LmOMjBhlHD+57A/ofqenQ6hbPFP80BxuXkdwRyOetef/Aj9lXwh+zpHer4a077AL7y/NP2iaXds34/1kj4/1jdPWsYqLneey/E0nJqP7vcwv2Ov2OdD/ZM+H/8AZunjzr64/wCPy7zIv2jbJMyfI0jhdolI4PPU+3su5fX9KAdwyRgntmn7hWs6spvmkZwpRjsf/9k=' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
</tr></table>
<!-- End Page links left/up/right //-->
<!-- Dynamic JAVA Script Section //-->
<script>
// disable our NAV pointers till later where we may re-enable them.
document.getElementById('Show-Right').style.display = 'none';
document.getElementById('Show-Left').style.display = 'none';
//
// This is the specific function that I need help with.
// Why does this modal pop up only after the actual query is done?
//
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
document.getElementById('myModal1').style.display = "none";
};
// Navigate left and right..
function AjaxNavigate(link)
{
xx = document.getElementById('Leftlink').value
xx = document.getElementById('Rightlink').value
if (link == 0)
{
// Back to the main page. Get the values that make who we are -- servername and count.
var count = document.getElementById('count').value;
var CurrentSystem = document.getElementById('serverID').value;
var x = '/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime());
location.replace('/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime()));
}
else
{
if (link == 1)
{
document.getElementById('serverID').value = document.getElementById('Rightlink').value
} else {
document.getElementById('serverID').value = document.getElementById('Leftlink').value
}
// we've moved left or right. Lets update.
AjaxInitialUpdate()
}
}
function AjaxCheckOutPassword() {
console.log("Checkout Code not yet written");
};
function AjaxInitialUpdate() {
var xhr = ""
var xhr = new XMLHttpRequest();
var count = document.getElementById('count').value;
var link = document.getElementById('serverID').value
document.getElementById('myModal1').style.display = "block"; // show we are updating everything..
document.getElementById('myModal2').style.display = "none"; // should already be hidden, but lets make sure..
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=refresh&server=' + link + '&count=' + count + '&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Response.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
WebFields = xhr.responseText.split("|");
document.getElementById("DynServerName").innerHTML = WebFields[0];
document.getElementById("DynAdminID").innerHTML = WebFields[1];
document.getElementById("DynLastCheckedout").innerHTML = WebFields[2];
document.getElementById("DynLastCheckedBy").innerHTML = WebFields[3];
document.getElementById("DynExpectedBack").innerHTML = WebFields[4];
document.getElementById("DynLastReset").innerHTML = WebFields[5];
document.getElementById("PassStatus").innerHTML = WebFields[6];
document.getElementById("DynEmailCheckIn").innerHTML = WebFields[7];
document.getElementById("DynEmailCheckOut").innerHTML = WebFields[8];
// if no comment, don't even dispay the table cells.
if (WebFields[9].slice(0,1) == "{" && WebFields[9].slice(-1) == "}" && WebFields[9] != "{}" )
{
var res = WebFields[9].split("{");
var res = res[1].split("}")[0];
document.getElementById("DynAccountPurpose").innerHTML = "<tr><td style='width: 474px;' colspan='2'><p><b>Account Comments:</b></p><p class='tab'>" + res + "</p></td></tr>";
}
else
{
document.getElementById("DynAccountPurpose").innerHTML = "";
console.log("No Comment");
};
// lets populate the nav buttons..
if (WebFields[10] == '\\')
{
// hide go left
document.getElementById('Show-Left').style.display = 'none';
document.getElementById("Leftlink").value = "0/0"
}
else
{
//Enable go left
document.getElementById('Show-Left').style.display = 'block';
document.getElementById('Leftlink').value = WebFields[10];
};
// lets populate the nav buttons..
if (WebFields[11] == "\\")
{
// hide go right
document.getElementById('Show-Right').style.display = 'none';
document.getElementById("Rightlink").value = "0/0";
}
else
{
// Enable go right
document.getElementById('Show-Right').style.display = 'block';
document.getElementById("Rightlink").value = WebFields[11];
};
document.getElementById('myModal1').style.display = "none";
}
if (xhr.status === 403) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Access Denied';
}
if (xhr.status === 404) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Unable to load';
};
}
else
{
document.getElementById("PassStatus").innerHTML = "Failed";
};
};
xhr.send(null);
};
// Now, load the initial value..
window.onload = AjaxInitialUpdate();
</script>
When I call AjaxChangePassword(), I expected the modal to open BEFORE the query.
As it is now, if I stop the server after the page loads, but before this function is started, the modal never pops up, then once I start the server side back up, and I see the query come in and get answers, only then does it pop up, and then only for a split second.
What am I doing wrong in the way I am calling it?
As I reviewed your code and found that in the function AjaxChangePassword firstly you opened modal and then called ajax then closed modal the problem is that basically javascript executes synchronously but if there is ajax call then it executes asynchronously, so according to that your modal opens and then call ajax untill ajax is busy in getting response before that next line will be executed that line is for modal close and this happens in the fraction of ms so you don't see anything, And you said that after ajax call modal is showing because in AjaxChangePassword the call back method is AjaxInitialUpdate and also in this method you opened modal then closed but remember in this method you closed modal in the call back method so it appears for some time and you can see so according to me just remove
document.getElementById('myModal1').style.display = "none";
this line from AjaxChangePassword method below is corrected AjaxChangePassword function
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('myModal1').style.display = "none";
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
};
and check. I may be wrong but check it.

auto refrsh api data

i need to refresh particular data line in every interval when the value change
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()+ randomnumber);
}, 1000);
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
document.getElementById('output').innerHTML=data;
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="output" style="margin:5px 0;">
</div>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</body></html>
Here i get all refreshed in every seconds. i need to refresh only a particular line
Hi Here I done as per your req, Just one line I have done, for other line do by your self, I just makes your string obj into obj and added table style.
js fiddle
html
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<div id="output" style="margin:5px 0;">
</div>
<table>
<tr>
<th style="margin-left:20px">exchange</th>
<th>fromSymbol</th>
<th>toSymbol</th>
<th> volume24h</th>
<th>volume24hTo</th>
</tr>
<tr>
<td>Bitfinex</td>
<td>BTC</td>
<td>USD</td>
<td id="volume24h">BTC</td>
<td id="volume24hTo">USD</td>
</tr>
</table>
java script
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()) + randomnumber;
}, 1000);
gettxt()
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
var dataTemp = JSON.parse(data);
document.getElementById('volume24h').innerHTML=dataTemp.Data[0].volume24h;
document.getElementById('volume24hTo').innerHTML=dataTemp.Data[0].volume24hTo;
console.log(dataTemp);
})
}

jquery - showing box with if statement by click on button when field is completed - quiz creation

I'm desperately trying to create something very simple for you!
Here's my problem:
I'd like to create a small quiz in which when someone writes anything in a field (), and then click the button "ok" (not sure if I should use a or a ), then 3 possibilities arise (for each case a box appearing under the field input):
The answer is exact and correctly written: then the text will be "Great job!"
The answer is almost correct, meaning that the word is not correctly written (we can define if necessary "almost answers"): the text will be "Almost there..."
The answer is completely wrong, the text will be "Try again!"
Right now I have that:
<body>
<div>
<table>
<tbody>
<tr>
<td>To whom it belongs?</td>
</tr>
<tr>
<td>
<img src="#" alt="Tim's coat" width="100%"/>
</td>
</tr>
<tr>
<td class="answer-box">
<input type="text" class="field-answer" placeholder="Write it there!">
<button id="showresult" class="button-answer" value="Ok">OK</button>
</td>
</tr>
<tr>
<td>
<div class="res" id="switch">Great job!</div>
<div class="res" id="switch2">Almost there...</div>
<div class="res" id="switch3">Try again!</div>
</td>
</tr>
</tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$(document).ready(function(){
$('.field-answer').bind('keyup', function(){
if("#showresult").click(function() {
if($.inArray($(this).val().toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g, ''), artist) >= 0){
$('#switch').show('good');
}
else if($.inArray($(this).val().toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g, ''), almostartist) >= 0){
$('#switch2').addClass('soso');
if{
$('#switch3').addClass('non');
}
else {
$('#switch3').removeClass('non');
}
});
});
}
</script>
But of course this is not working...
In case, my CSS is here:
.res {
display: none;
color: white;
font-weight: bold;
text-align: center;
background-color: #490058;
height: 75px;
max-width: 100%;
line-height: 70px;
font-size: 140%;
}
.res.good {
display: block;
}
.res.soso {
display: block;
}
.res.non {
display: block;
}
.answer-box {
text-align: center;
}
.button-answer {
border: none;
background-color: #490058;
color: white;
font-size: 120%;
font-weight: bold;
padding: 8px;
left: 260px;
}
.field-answer {
text-align: center;
border: none;
border-bottom: 2px solid black;
background-color: transparent;
max-width: 230px;
height: 40px;
font-size: 20px;
text-transform: uppercase;
outline: 0;
}
Someone could help me to figure that out, please?
I'm quite sure I'm not far, but cannot solve it...
If you need more precisions on stuffs, please don't hesitate! ;)
Thanks guys!
Baptiste
A slightly different approach - no better than any other suggestion - FIDDLE.
JS
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$('.field-answer').focus(function(){
$('.res').css('display', 'none');
$(':input').val('');
});
$('#showresult').on('click', function(){
useranswer = $('.field-answer').val();
useranswer = useranswer.toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g);
if( $.inArray( useranswer, artist ) === 0 )
{
$('#switch1').css('display', 'block');
}
else if ( $.inArray( useranswer, almostartist ) >= 0 )
{
$('#switch2').css('display', 'block');
}
else //if ( $.inArray( useranswer, almostartist ) < 0 )
{
$('#switch3').css('display', 'block');
}
});
your whole function is bound in to 'keyup' event.
keyup event only occurs once when key is released from pressed.
try deleting bind('keyup', function)
I've found a solution to your problems.
Check this Fiddle
In this script every time you click on the button the field text is compared with the values of the array
Depending on the value of the the corrisponding div is showed.
code
<script type="text/javascript">
$(document).ready(function(){
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$("#showresult").click(function() {
var text=$('.field-answer').val();
if(artist.indexOf(text) > -1){
$('#switch').show();
}
else if(almostartist.indexOf(text) > -1){
$('#switch2').show();
}
else{$('#switch3').show();}
});
});
</script>
if you want the message appears on keyup you have to use this code
<script type="text/javascript">
$(document).ready(function(){
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$(".field-answer").on('keyup',function() {
$('.res').hide()
var text=$('.field-answer').val().toLowerCase();
if(artist.indexOf(text) > -1){
$('#switch').show();
}
else if(almostartist.indexOf(text) > -1){
$('#switch2').show();
}
else{$('#switch3').show();}
});
});
</script>
If you like one of these solutions remember to falg in green my answer ;) thanks.

Using JavaScript to change text on the page every half-second

So, what I'm hoping to do is change the text inside a set of <p> tags every half-second. The set of tags in question is in this block of code in my body:
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
Right below the above code I have the JavaScript that should call a function every half-second:
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
I have the function changeMatrixText defined inside my head:
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
As you see, that's supposed to set the text to a random string of 0's and 1's. But it's not working. Any idea why?
Just in case you need to see my entire code .....
<html>
<head>
<title>Simple encrypt/decrypt</title>
<style type="text/css">
body
{
background-color: #A9F5F2;
width: 900px;
padding: 0px;
}
.outerdiv
{
margin: 5px;
border: 2px solid #FF8000;
background-color: #FFFFFF;
}
.outerdiv > p
{
margin: 5px;
word-wrap:break-word
}
.outerdiv > h1
{
margin: 5px;
}
#col1
{
width: 500x;
height: 800px;
float: left;
}
#col2
{
width: 295px;
height: 1500px;
float: right;
font-family: Courier New;
overflow: hidden;
}
#title1div
{
font-family: Arial;
width: 100%;
}
#insctdiv
{
font-family: Arial;
width: 100%;
}
#iptdiv
{
height: 400px;
width: 100%;
}
#buttonsdiv
{
text-align: center;
width: 100%;
}
#inputText
{
width: 100%;
height: 100%;
resize: none;
}
</style>
<script type="text/javascript">
function encrypt()
{
var text = document.getElementById("inputText").value;
newstring = "";
/* Make newstring a string of the bit representations of
the ASCII values of its thisCharacters in order.
*/
for (var i = 0, j = text.length; i < j; i++)
{
bits = text.charCodeAt(i).toString(2);
newstring += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress newstring by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
newstring = newstring.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
document.getElementById("inputText").value = newstring;
}
function decrypt()
{
var text = document.getElementById("inputText").value;
text = text.trim();
text.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
document.getElementById("inputText").value = text;
}
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
</script>
</head>
<body>
<div id="col1">
<div class="outerdiv" id="title1div">
<h1>Reversible text encryption algorithm</h1>
</div>
<div class="outerdiv" id="insctdiv">
<p>Type in or paste text below, then click <b>Encrypt</b> or <b>Decrypt</b></p>
</div>
<div class="outerdiv" id="iptdiv">
<textarea id="inputText" scrolling="yes"></textarea>
</div>
<div class="outerdiv" id="buttonsdiv">
<button onclick="encrypt()"><b>Encrypt</b></button>
<button onclick="decrypt()"><b>Decrypt</b></button>
</div>
</div>
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
</body>
</html>
In essence, I'm trying to make the right column of my page keep printing inside a new string of 0's and 1's every half-second, kinda like on the computer screen on the movie The Matrix, if you catch my drift.
According to MDN, the elements with a value attribute include <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>. You'll need to set the innerHTML instead.
document.getElementById("matrixText").value = newtext;
to
document.getElementById("matrixText").innerHTML = newtext;
and
setInterval("changeMatrixText()", 500);
to
setInterval(changeMatrixText, 500);
Working Demo
document.getElementById("matrixText").value = newtext;
.value is used for form fields instead use
document.getElementById("matrixText").innerHTML = newtext;
in your changeMatrixText function
Here's an example of how you can do this:
http://jsfiddle.net/35W4Z/
The main difference is that a <p> element doesn't have a .value attribute. Instead, use the innerHTML attribute (as shown in the JSFiddle example)
Hope this helps!
Well for fun, I stuck this in a fiddle: http://jsfiddle.net/jdmA5/1/
So two things, mostly:
1) You can't set the "value" of a div element. You have to set the .innerHTML:
document.getElementById("matrixText").innerHTML = newtext;
2) This could be due to the fact I built this out in fiddle, but setInterval is notorious for not running like you expect unless you give each iteration its own memory space. I did this by wrapping the call to changeMatrix in a anonymous function:
setInterval(function() {changeMatrixText();}, 500);
Check out the jsfiddle link to see it in action.
Have you tried changing the setInterval method to accept the first argument as the function itself (the name, minus the parentheses), rather than a string...
As you are not passing any parameters explicitly, you can invoke the function as follows:
setInterval(changeMatrixText, 500);
Should you have needed to supply some parameters, then the following would work:
setInterval(function() {
changeMatrixText(myParam1, myParam2); // etc, etc
}, 500);

Categories