I am making a terminal window in HTML/JavaScript and am using a textarea for input. I would like to prevent sections of the text in the textarea from being deleted. For example, if I had the text in the textarea "C:\>Random Code" I would like to prevent the user deleting the "C:\>" text. Is this possible using javascript?
Assuming jQuery, this script will listen for keystrokes, and if any of the required text can't be found (ie: user tries to delete it) it will add itself right back in there:
var requiredText = 'C:>';
$('textarea').on('input',function() {
if (String($(this).val()).indexOf(requiredText) == -1) {
$(this).val(requiredText);
}
}
You cannot make a section of textarea uneditable (only the whole control).
You can use various JavaScript trickery (listening to keypress events and cancelling event using event.preventDefault if the user wants to do something that you do not want to allow)
Another solution is to, instead of having an undeletable section of the input, to automatically append (or prepend ) a predefined string to the user input (and conveneintly display it for the user in some way).
Update:
So, my solution would look like this:
var requiredText = 'C:>';
$('textarea').on('keyup',function(event) {
if (GetSelectionStart(this) < requiredText.length){
event.preventDefault();
event.stopPropagation();
}
}
Where GetSelectionStart is a function that tells the beginning of the selected text (or caret position, if no text range is selected). For some possible implementations, see e. g. Caret position in textarea, in characters from the start
This function assumes that requiredText is always at the beginning of the string. But of course, it can be adapted for more complex scenarios.
Related
I want to copy input from one textarea to another textarea in real-time. This is not a HTML editor or rich text editor. Just plain simple text without any markup.
This is what I am doing:
a. I can detect the point at which the cursor was clicked in the source text area using the following (on mouseup)
$("#txt1")[0].selectionStart)
b. I can detect the text selection using selectionStart and selectionEnd properties on mouseup.
This allows me to keep track of delete to be reflected in the other textarea. That is if delete is the key pressed, and a selection was made I know what was deleted to be relected in the target text area.
c. Where I am stuck is the simple issue of new characters entered. I think keeping track of key pressed would be the inefficient approach as I would have to check if control, alt, shift keys, among others were also held down. Besides there is the issue of repeatedy keys presses. The efficient way is possibly to get the characters actually entered from the source text area and NOT based upon key pressed.
Questions:
How do I get characters entered in the source textarea?
Is there a better way to update the target textarea in real-time? One way will be to continually update the content from the source to the target at regular interval but that would be inefficient. Any other approach?
I am open to using a contentEditable div in place of a textarea.
I need a solution that can work across different device types.
How do I get characters entered in the source textarea?
Just handle the input event of the first textarea and make the second textarea have the same value as the first.
let two = document.getElementById("two");
document.getElementById("one").addEventListener("input", function(){
two.value = this.value;
});
<textarea id="one"></textarea>
<textarea id="two"></textarea>
On my page, I have a contenteditable div element. When a specific key is pressed, a function executes:
function bla(element) {
if (getSelectionHtml() != "") {
replaceSelectedText("text");
}
}
getSelectionHtml() checks if something is selected by the user. replaceSelectedText(text) replaces the selected text with a given string. Both functions are working properly.
After the selected text has been replaced, I want to 'cancel' the user's selection, as the selection is now equal to the 'new' string, so just deleting the text is not an option.
I tried this:
element.style.userSelect = "none";
element.style.userSelect = "text;
But it didn't work because userSelect: none doesn't seem to change anything in a div element with contenteditable. Also, this solution looks pretty ugly for such a simple problem.
So, how can I cancel the user's selection?
I think you want to remove selection completely. You can do so once you have replaced the string with
window.getSelection().removeAllRanges()
So basically, once you select the range of content, you can get the range with window.getSelection() method which returns set of details about selected content. It has many functions to alter the range and remove the range completely. To know more, you can read in brief of all supported methods Selection API
What I'm aiming for
When the user focuses the input: if it's empty, we insert the prefix text and move the cursor to the end. It should also work if they tab into the input.
Context/demo
I'm making a jQuery plugin that adds a flag dropdown next to an telephone number input. When the user focuses the input, it gets populated with a little prefix (the selected country's dial code). Demo here.
Problems
By default, the cursor will appear where ever they clicked i.e. potentially in the middle of the prefix). I found this mini plugin to move the cursor to the end, which works well if you put it in a click event handler, BUT then this wont fire if you tab into the input. I tried putting it in a focus event handler instead, but that didn't work (I think because the click event is fired after the focus event).
Bonus points
For a simple, elegant solution, using no global variables, and the least number of event listeners possible. Also if possible, don't show the cursor where they are clicking before moving it to the end.
This is the best solution I have come up with so far. It ticks all the boxes, except it's not the most elegant solution - I feel like I might be missing something obvious. Ideally, it would only require one event listener.
var input = $("input"),
prefix = "prefix ";
input.focus(function(e) {
if (!input.val()) {
input.val(prefix);
}
});
input.mousedown(function(e) {
// mousedown decides where the cursor goes, so if we're focusing
// we must prevent this from happening
if (!input.is(":focus") && !input.val()) {
e.preventDefault();
// but this also cancels the focus, so we must trigger that manually
input.focus();
putCursorAtEnd(input);
}
});
Here's a codepen demo.
Focus, clear value, then revert to original value
1st save the value to a temporary variable.
2ndly clear the input field
3rdly focus that empty field & again paste the saved value from temporary variable.
it will always focus to the end of the field.
$tempVal = $("#digibox_otp").val();
$("#digibox_otp").val('');
$("#digibox_otp").focus().val($tempVal);
How to prevent the change of certain elements, tokens, within a textarea with javascript or jquery? For instance I have this string in an input
this is normal text {this can't be changed 1}. This is more text. {This can't be changed 2 }. And some more text
If a user tries to change text within the curly brackets I want to prevent that from happening.
I thought of finding the indexes of the start and stop indexes of the tokens and when a user tries to change an element, I would see if it falls within that range.
Is there a different approach that I can use?
You could use a regular expression to read everything between {} into an array when the page loads. Then when the form submits do that same thing again and compare them to make sure they are the same.
You should build a regular expression that validates the validity of the text. on every keydown event in the textarea revalidate the regex and notify the user / prevent the keypress.
As text can also be changes in other ways (paste, autocomplete, etc.) you should also validate on change event of the textarea.
I have a table which is filled with data from a database. Some javascript allows a user to select certain rows and take some actions. I allow users to click one row and then to shift click another row to create a group (as well as alt-click to select/deselect individual rows).
The problem is I don't like how the text highlights when they shift click. Is there some CSS setting or javascript/jQuery solution to disable the selectable text (cross browser preferablly or just in firefox).
If possible I also want to be able to let the user select text to copy and paste sometimes or inside a textbox form input inside the same table so I would like to be able to enable and disable the selecting of text somehow. Any ideas?
this should do the trick:
$('td').disableSelection();
example:
http://jsfiddle.net/GhfuJ/1/
Here's one way you could completely disable text selection:
$("selector").bind($.support.selectstart ? "selectstart" : "mousedown", function(event) {
event.preventDefault();
});
This is how jQueryUI implements its disableSelection() method.
You could tailor your selector to exclude textarea elements, or wrap code inside the event handler with an if block that evaluates a boolean that gets set under certain circumstances (For example, you could turn on booleans when the user is clicking or shift/alt + clicking).