So I can append text to a textarea using this method
document.getElementById('myArea').value += msg;
This tacks the new input onto the end of the current input.
Suppose the textarea already contains text. Suppose also that using "=" instead of "+=" and inputting the values textarea already had along with the new ones is not a possible solution in this context
How would one input new text to this textarea on the correct line and in the correct position with respect to the text that is already in place?
Here is a YouTube video demonstrating the problem
https://www.youtube.com/watch?v=GpwEuI3_73I&feature=youtu.be
UPDATE:
Instead of sending one letter at a time, I sent the whole textarea each time a key is pressed. Obviously more computationally taxing, but that's the only solution I have right now. I am still interested in hearing any better solutions if you have one!
I'm assuming you send only the last character typed (as in your original approach), and it is stored in a variable named "newChar".
Take this as pseudo-code, although I hope it does not require many changes to actually work:
// deserialize the text of the target textearea
var txt = targetTextarea.text;
var txtAsArray = txt.split(/\r?\n/);
var txtLine = txtAsArray[cursorRowNum];
// write the new character in the right position (but in memory)
txtLine = txtLine.substr(0, cursorColNum) + newChar + txtLine.substr(cursorColNum);
// now serialize the text back and update the target textarea
txtAsArray[cursorRowNum] = txtLine;
txt = txtAsArray.join("\n");
targetTextarea.text = txt;
A reference used was: How in node to split string by newline ('\n')?
Regarding performance, there is no additional network activity here, and we are accessing the DOM only twice (first and last line). Remember than accessing the DOM is around 100 times slower than plain variables in memory as shown by http://www.phpied.com/dom-access-optimization/ .
That "txt = txtAsArray.join("\n");" might need to be "txt = txtAsArray.join("\r\n");" on Windows. Detecting if you are in one or the other is explained at How to find the operating system version using JavaScript as pointed by Angel Joseph Piscola.
Hi this will add text to existing text in textarea
i have try that
var msg = "Hi How are you ?";
document.getElementById('myArea').value += msg;
Related
I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);
The short version: I work in a hospital and am attempting to create a safer, more efficient downtime version of the forms we send with blood components for transfusion. Currently we handwrite or type the donor identification number (DIN) and the product code of the unit onto this form, but ideally these are scanned, as they are ISBT 128 barcodes on the unit.
Scanning a DIN gives me ~=W11512003927826 - I would like to have the first two characters (non-alphanumeric) removed, and if possible, the last two. I've been able to accomplish the second task by simply limiting the character input of the field, which is standard and should work fine.
This also applies to the product code, which scans as ~=<E0785V00 and does not need the first three characters.
I've tried a few methods including some Javascript that was supposed to limit the field to only alphanumeric characters, which I assume is probably the simplest way to handle all of this, but either the code was not in the correct syntax for Adobe or I implemented it incorrectly. I am not familiar with JS at all and am just learning form creation.
If anyone has any advice I'd appreciate any help at all. Thanks in advance!
Edit: So far I've tried these three. I'm using these as an action (run a javascript) on mouse exit and also tried on blur.
const alphanumeric = /[a-zA-Z0-9]/g;
const string = "abc-ABC-012";
const result = string.match(alphanumeric).join("");
console.log(result); // abcABC012
const nonalphanumeric = /[_\W]/g;
const string = "abc-ABC-012";
const result = string.replace(nonalphanumeric, "");
console.log(result); // abcABC012
const string = "aa-aa";
const result = string.slice(2, -2);
console.log(string); // aa-aa
console.log(result); // -
I recommend you setup "On Blur" event handlers for each field that needs to accept scanned in data. For the DIN field, adjust the value using:
var field = this.getField("DINField");
field.value = field.value.replace(/^~=(.+)..$/, '$1');
The code above assumes the field is named DINField. Change as appropriate. It is important to use logic like a RegExp for modifying the value because the on-blur event can fire multiple times per field. The code above will only remove the ~= app-id and last two characters once.
Likewise, for the product-id, set on "On Blur" handler to:
var field = this.getField("ProductField");
field.value = field.value.replace(/^~=<(.+)$/, '$1');
The code above assumes the field is named ProductField. This reg-ex only removes the app-id (and not the last two characters).
i'm trying to live edit a text box value so that the result will be split every two character,
adding a column and starting from some default character.
what i have till now is this code, that obviously doesn't work:
$('#textboxtext').keyup(function (){
var text = $("#textboxtext").val();
//$(text).attr('maxlength', '12');
var splitted = text.match(/.{2}|.{1,2}/g);
var result = ("B8:27:EB:" + splitted.join(':'));
});
i need the live split and the default character inside the textbox but i really don't know where to start...
From your code, it seems like you're trying to create a text box that has some very specific behavior. It looks like it needs to format its value in such a way that it always begins with certain 'prefix' of B8:27:EB:, and every subsequent pair of characters is is separated by a :. This is actually a very complex behavior and you have to consider a number of different interactions (e.g. what happens when the user attempts to delete or modify the prefix). I usually try to avoid such complex controls if possible, however here is a quick implementation:
$('#textboxtext').keyup(function (e){
var prefix = "B8:27:EB:",
text = $(this).val(),
splitted, result;
if (text.indexOf(prefix) == 0)
text = text.substr(9);
else if (prefix.indexOf(text) == 0)
text = "";
text = text.replace(/:/g, '');
splitted = text.match(/.{1,2}/g) || [];
result = prefix + splitted.join(':');
$(this).val(result);
});
Demonstration
Type inside the text box and see what happens. Also note, there are all kinds of interaction that this implementation doesn't account for (e.g. right-clicking and pasting into the text box), but it's a start.
I've found some code on a site and been tinkering with it a little. It involves some functions to add and delete students (the add code is below) from an array - into a value field. I can't figure out why in tarnations we need this extra piece of code, however.
Here is the js code:
var students = ['Paulie', 'Nicole', 'Kevin', 'Mare'];
function addClick(){
var addRemove = document.getElementById('addRemoveStudent');
var studentsBox = document.getElementById('studentsBox')
students.push(addRemove.value);
addRemove.value = '';
studentsBox.value = students.join(', ');
}
My question is: Why do we need the addRemove.value = ''; line? I've tested it without that code and it still works fine. Is there a reason we need that?
I can send more code including the HTML but didn't what to overwhelm anyone with the volume.
Thanks so much in advance!
-Anthony
It's not necessary. I guess semantically it means to clear the addRemove box first before replacing the value.
It's optional, but it's simply to clear the text box so the user can enter a brand new value if they want to run the function again.
To clear the value of the addRemoveStudent ( I think it is a input type="text") Just for it, It is not needed in the array. Just to clear the value of that control.
Presumably addRemove is an input element. Setting the value property of an input element to an empty string '' means that the input is emptied: it will have no text in it.
My guess is that this function is run when a button is clicked, so it adds a new student to the array, updates the studentsBox field with the right data, and clears the input element so you can add more if the user wishes to do so.
Ok, I'm a bit of a n00b when it comes to JS (I'm not the greatest programmer) so please be gentle - specially if my questions been asked already somewhere and I'm too stupid to find the right answer. Self deprecation out of the way, let's get to the question.
Problem
There is a site me and a large group of friends frequently use which doesn't display all the information we may like to know - in this case an airline bookings site and the class of travel.
While the information is buried in the code of the page, it isn't displayed anywhere to the user.
Using a Greasemonkey script, I'd like to liberate this piece of information and display it in a suitable format.
Here's the psuedocode of what I'm looking to do.
Search dom for specified element
define variables
Find a string of text
If found
Set result to a variable
Write contents to page at a specific location (before a specified div)
If not found
Do nothing
I think I've achieved most of it so far, except for the key bits of:
Searching for the string: The page needs to search for the following piece of text in the page HEAD:
mileageRequest += "&CLASSES=S,S-S,S-S";
The Content I need to extract and store is between the second equals (=) sign and the last comma ("). The contents of this area can be any letter between A-Z.
I'm not fussed about splitting it up into an array so I could use the elements individually at this stage.
Writing the result to a location: Taking that found piece of text and writing it to another location.
Code so far
This is what I've come up so far, with bits missing highlighted.
buttons = document.getElementById('buttons');
''Search goes here
var flightClasses = document.createElement("div");
flightClasses.innerHTML = '<div id="flightClasses"> ' +
'<h2>Travel classes</h2>' +
'For the above segments, your flight classes are as follows:' +
'write result here' +
'</div>';
main.parentNode.insertBefore(flightClasses, buttons);
If anyone could help me, or point me in the right direction to finish this off I'd appreciate it.
The Content I need to extract and store is between the second equals (=) sign and the last comma (").
Do you mean "is between the second equals (=) sign and the last quote (")"?
And I assume that this:
mileageRequest += "&CLASSES=S,S-S,S-S";
is in a script tag?
If so then it looks like there will be a JS variable on the page called mileageRequest which you can access from Greasemonkey with unsafeWindow.mileageRequest and assuming that you can access the data you want with something like:
// check that the mileageRequest variable exists
if(unsafeWindow.mileageRequest){
// it exists
var myString = unsafeWindow.mileageRequest.match(/&CLASSES=([^&=]*)/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my sting does not exist
}
}
else {
// it does not exist
}
or you can try:
var myString = document.getElementsByTagName('head')[0].innerHTML.match(/mileageRequest\s*\+=\s*"&CLASSES=([^"]*)";/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my string does not exist
}