Get the value of a textbox during cut event - javascript

I have trapped the cut event (jquery) on a textbox. What I want is to get the text on the textbox during the cut event is triggered.
I've tried accessing the data the user cut via evt.originalEvent.clipboardData.getData('text') but returns undefined.
My goal is to know if the user cut all the text (textbox is now empty) or not.
Thanks in advance

You can setTimeout with a duration of 0, which schedules a function for immediate execution. The nice thing is that the function will execute once the text has already been cut, so you can check then if your textarea is empty (which would mean that the user has cut all the text):
var ta = $('#YOUR_TEXTAREA');
ta.bind('cut', function() {
setTimeout(function(){
if (!ta.val()) {
// user cut the whole text.
}
},0);
});
You might also want to add a check before the setTimeout to test whether there is any text in the textarea before the text gets cut (if the user presses Ctrl^X without any text being selected, the cut event still triggers)

Hope I got you right:
In jQuery you could use something like this to see if a textbox is empty on every user's keyup:
var txt;
$('#textbox_ID').live('keyup', function() {
txt = $(this).val().length;
if(txt < 1) {
alert("textbox is empty");
}
});
This should work, because everytime the user releases a key and has the textbox focused, it checks if it's empty.

I would suggest looking at this, JavaScript get clipboard data on paste event (Cross browser), it is for the paste event but I'm sure you could do something similar and compare the current value to that on the clipboard, if they are exactly the same than the input would be empty, otherwise not.

Related

On focus input: insert value and move cursor to end

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);

HTML textarea prevent some text from being deleted

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.

really simple javascript to remove value in text box

iv got a really simple javascript question. Ill be using query for parts of it here but there are akin ways of doing it via javascript. basically, I'm writing a little script that makes it so when you click a text box with a value in it, it will take out the value so your can type (ex for most username boxes they have a little note in there). there are probably much better ways of doing this (i can already think of some) so feel free to suggest them as well. anyways I got that part running easily, the problem is that whenever a user clicks again all the data is removed, so if they just want to adjust something they can't. to solve this (ill show code in sec) i put a check variable and an if. this is what it looks like. (it doesn't work, btw)
var unumber = 0;
var pnumber = 0;
if(unumber<1){
$('#username').click(function(){
unumber = 1;
$('#username').val('');
});
};
if(pnumber<1){
$('#password').click(function(){
$('#password').val('');
pnumber = 1;
});
};
what I'm assuming happens is that every time some one clicks the variables are reset, and this leads to a more general question if this is this case, why would the whole script, not just the event handler, run? Im new to javascript so forgive me if this is a stupid question. Anyways, this is a really simple script and there are better and more efficient ways to do it, but how can it be done this way?
Your check for number less than 1, should be within the click handler
var unumber = 0;
var pnumber = 0;
$('#username').click(function(){
if(unumber<1){
unumber = 1;
$('#username').val('');
}
});
$('#password').click(function(){
if(pnumber<1){
pnumber = 1;
$('#password').val('');
}
});
Note that this is not very robust, it doesn't handle tabbing into the fields. To fix that, handle the focus event.
Another problem is that you don't get the message back if you don't type anything and leave the field. A better approach is to compare against the initial value when the field receives focus. If there's nothing in there when you leave the field, restore to the original value.
Here's a jQuery plugin for creating these placeholders: https://github.com/mathiasbynens/Placeholder-jQuery-Plugin
Also, newer browsers support a placeholder attribute that does exactly that http://www.paciellogroup.com/blog/2011/02/html5-accessibility-chops-the-placeholder-attribute/
I'd say the best way of doing this is to have a clear button inside the text input. See here for an example : How do I put a clear button inside my HTML text input box like the iPhone does?
No need for the messy number checking, use data on the element in question
This should work for you.
$('#username,#password').focus(function(){
if(!$(this).data('seen')) {
$(this).data('seen',true);
$(this).val('');
}
});
http://jsfiddle.net/DeZ7D/
You could store the placeholder and replace back on blur if the user hasn't entered anything.
more detailed implementation here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

jQuery - set max length for textarea

I want to have a textarea with a maximum length, and show the user how many characters are left (as it's done on twitter), but I can't seem to get it to be as good.
The requirements are:
Must show the current number of characters they've typed
Must remain accurate when a key is held down
Must remain accurate when backspace/delete is used
Must remain accurate when text in the box is selected and cut/delete by using the right click menu
Must allow the user to go over the limit (I hate it when a field actually prevents me from going over, it makes it harder to edit it down)
Is there a jQuery plugin to do this? Or is there a simple javascript way of doing it (the onChange method doesn't update as they're typing, and keydown/keyup would have troubles with mouse changes)
At the moment it seems like the best way is to have a function to do what I want (check the length and update the message), call it with keydown/keyup/change, and also poll it a few times per second. Is there a better way?
What you usually do is attach multiple event handlers pointing to a validating function, but you won't be able to stop the rightclick/paste with this...
$(document).ready(function() {
$("#myTextArea").live("change keydown keyup keypress", function() {
validate();
});
});
function validate() {
// validates #myTextArea
}
try this
$("#textarea").on('input',function(){
if(this.value.length > 50) {
alert("u cant input more.");
this.value = this.value.substring(0,50);
}
$('#counter').html(this.value.length + '/50');
});
maybe this code help u

Validating a text box value using JavaScript

I have a textbox.T he user will be entering entering a number in this box. The user should enter two digits followed by a period "." and another digit. It would look something like 22.3 or 00.5 or 01.2.
If the textbox is not empty, I want to enforce a function which validates the value entered by the user (and gives them an alert if the value entered is not according to the format mentioned above). This function needs to be triggered when the textbox loses its focus. I am not sure how to go ahead in writing this function as I am still new to this.
Any help would be appreciated.
p.s. This function should be triggered each time there is a change in the value. Like suppose, the user enters a value 22, then when the textbox loses its focus, the JavaScript function should be triggered giving them an alert asking the user to change it to the accepted format which is 22.0.The function should be triggered again when the textbox loses its focus (after the change has been done). This time there would not be an alert since the user entered it in the right format.
Excuse the Prototype specific code, but maybe you'll get the gist of it. You'll want to listen on the "onblur" event of the textarea, and then validate the entered value with a regular expression.
Event.observe('textboxId', blur, function() {
var val = $F('textboxId');
if (/^\d{2}\.\d$/.test(val)) {
alert('Invalid value');
}
});
If you're not familiar with any javascript frameworks, and just want to get this working, try this:
<textarea onblur="validate(this.value);"></textarea>
<script type="text/javascript">
function validate(val) {
if (/^\d{2}\.\d$/.test(val)) {
alert('Invalid value');
}
}
</script>
Purists, please don't punish me for adding this.

Categories

Resources