How to remove carriage return char after it's pressed? - actionscript-3

I have a textarea which is restricted to input only numbers. I want to remove carriage return char after user presses enter key. Here's my code:
// Change tempo
function changeTempo(event:KeyboardEvent):void {
if (event.charCode == 13) {
// Some code here
}
// Remove enter char
removeCarriageReturnsAndNewLines(tempo_txt.text);
}
function removeCarriageReturnsAndNewLines($myString:String):String {
var newString:String;
var findCarriageReturnRegExp:RegExp = new RegExp("\r", "gi");
newString = $myString.replace(findCarriageReturnRegExp, "");
var findNewLineRegExp:RegExp = new RegExp("\n", "gi");
newString = newString.replace(findNewLineRegExp, "");
return newString;
}

I would say the easiest way is to listen to text input, something like this:
var t:TextArea = this.ta; //ta is on the timeline
t.restrict = "0-9"; //restricts the input only to numbers
t.addEventListener(TextEvent.TEXT_INPUT, onTextInput, true); //use capture phase to be able to prevent the default behavior (text input)
function onTextInput(e:TextEvent):void {
if(e.text.indexOf("\n") > -1) {
e.preventDefault(); //prevent the default behavior of the field
}
}
I cannot test this right now but I guess it should work without problems.

Related

Google Chrome and Safari on MacOS grabs the character preceding the selected text when you drag'n'drop it into <textarea>

Clean textarea code (as in sandbox) without any side factors (like scripts and specific styles) its work via drag'n'drop in the Chrome browser is followed by a strange phenomenon.
<textarea cols="80" rows="10">
row1w1 row1w2 row1w3 row1w4 row1w5
row2w1 row2w2 row2w3 row2w4 row2w5
row3w1 row3w2 row3w3 row3w4 row3w5
row4w1 row4w2 row4w3 row4w4 row4w5
row5w1 row5w2 row5w3 row5w4 row5w5
row6w1 row6w2 row6w3 row6w4 row6w5
row7w1 row7w2 row7w3 row7w4 row7w5
</textarea>
For example, I drag the first word from any line somewhere like in the GIF image.
Along with the word, for some reason the drag-n-drop event grabs the character before the word (in this case, it's a line break character), even though that character was not selected. It is "compensated", if I may say so, by a space put before the word inserted in the new place. In some cases, this space can stand before the word, after the word and even turn into two spaces on both sides of the word, and sometimes does not appear at all.
The actual question is. Is there a way to make Chrome behave like a text editor or like Firefox? Is there a standard somewhere, or at least some description of how the phenomenon works, when it puts a space and when it doesn't?
I tried to solve this problem with a script. But the code works very crudely. For example, I can not track the difference between moving the selected text one character forward or backward. I think there is a better solution.
// If Google Chrome used
if (/Chrome/.test(window.navigator.userAgent)) {
// This variable handles source drag info
let dragging = null;
// This flag indicates whether the browser has captured a character before the word
let captureFlag = null;
// DragStart event handler
textarea.ondragstart = (e) => {
// First of all, аt this point we can read the initial state before dragging
const {
value,
selectionStart,
selectionEnd
} = textarea;
// Selected text
const selectionData = value.substring(selectionStart, selectionEnd);
// And keep the symbol before of the selected word
const selectionBefore = selectionStart ? value[selectionStart - 1] : '';
dragging = {
selectionStart,
selectionEnd,
selectionData,
selectionBefore
};
}
// Input event handler
textarea.oninput = (e) => {
// When dragging, this event is triggered twice
if (e.inputType == 'deleteByDrag') {
// At this point the highlighted word has already been deleted.
const {
selectionStart
} = textarea;
// If the cursor moved one character backward,
// the browser has definitely captured this character
captureFlag = dragging && selectionStart == (dragging.selectionStart - 1);
} else if (e.inputType == 'insertFromDrop') {
// At this point, the selected word is already inserted in its new location.
if (dragging) {
// Chrome browser leaves the word selected.
const {
value,
selectionStart,
selectionEnd
} = textarea;
// First we cut out what is inserted from the value
let newValue = value.substr(0, selectionStart) + value.substr(selectionEnd);
// If the browser does grab a character before selecting
if (captureFlag && dragging.selectionStart > 0) {
// Let's calculate his position
const insertPos = dragging.selectionStart - 1;
// Put the missing symbol back in place
newValue = newValue.substr(0, insertPos) +
dragging.selectionBefore +
newValue.substr(insertPos);
}
// Next, we have to determine the offset.
// If the pasted text was inserted somewhere after the deletion,
// we need to add to the offset one character that we just inserted
const offset = (captureFlag && (selectionStart > dragging.selectionStart)) ? 1 : 0;
// Now let's count the positions where we insert the originally selected text
const newSelectionStart = selectionStart + offset;
const newSelectionEnd = dragging.selectionEnd - dragging.selectionStart +
selectionStart + offset;
// Insert text that was originally selected (still in the dragstart event)
newValue = newValue.substr(0, newSelectionStart) +
dragging.selectionData +
newValue.substr(newSelectionStart);
// Apply the new value
textarea.value = newValue;
// And let's select this area of text like the browser
textarea.setSelectionRange(newSelectionStart, newSelectionEnd, "none");
}
}
}
// Reset the variables when the drag is finished
textarea.ondragend = () => {
dragging = null;
captureFlag = null
};
}
<textarea id="textarea" cols="80" rows="10">
row1w1 row1w2 row1w3 row1w4 row1w5
row2w1 row2w2 row2w3 row2w4 row2w5
row3w1 row3w2 row3w3 row3w4 row3w5
row4w1 row4w2 row4w3 row4w4 row4w5
row5w1 row5w2 row5w3 row5w4 row5w5
row6w1 row6w2 row6w3 row6w4 row6w5
row7w1 row7w2 row7w3 row7w4 row7w5
</textarea>
UPDATE
I was fixed to track the dragging of the word one character backward or forward.
// If Google Chrome used
if (/Chrome/.test(window.navigator.userAgent)) {
// This variable handles source drag info
let dragging = null;
// This flag indicates whether the browser has captured a character before the word
let captureFlag = null;
// DragStart event handler
textarea.ondragstart = (e) => {
// First of all, аt this point we can read the initial state before dragging
const {
value,
selectionStart,
selectionEnd
} = textarea;
// Selected text
const selectionData = value.substring(selectionStart, selectionEnd);
// And keep the symbol before of the selected word
const selectionBefore = selectionStart ? value[selectionStart - 1] : '';
// Save drag position
dragging = {
selectionStart,
selectionEnd,
selectionData,
selectionBefore,
dragLayerX: e.layerX,
dragLayerY: e.layerY,
dropLayerX: -1,
dropLayerY: -1,
};
}
// drop event handler
textarea.ondrop = (e) => {
// Save drop position
dragging.dropLayerX = e.layerX;
dragging.dropLayerY = e.layerY;
}
// Input event handler
textarea.oninput = (e) => {
// When dragging, this event is triggered twice
if (e.inputType == 'deleteByDrag') {
// At this point the highlighted word has already been deleted.
const {
selectionStart
} = textarea;
// If the cursor moved one character backward,
// the browser has definitely captured this character
captureFlag = dragging && selectionStart == (dragging.selectionStart - 1);
} else if (e.inputType == 'insertFromDrop') {
// At this point, the selected word is already inserted in its new location.
if (dragging) {
// Chrome browser leaves the word selected.
const {
value,
selectionStart,
selectionEnd
} = textarea;
// First we cut out what is inserted from the value
let newValue = value.substr(0, selectionStart) + value.substr(selectionEnd);
// If the browser does grab a character before selecting
if (captureFlag && dragging.selectionStart > 0) {
// Let's calculate his position
const insertPos = dragging.selectionStart - 1;
// Put the missing symbol back in place
newValue = newValue.substr(0, insertPos) +
dragging.selectionBefore +
newValue.substr(insertPos);
}
// Next, we have to determine the offset.
let offset;
// If text was dragged from end of row and dropped to start of next row
if(selectionStart == dragging.selectionStart){
offset = 1;
}
// If text was dragging on one char backward or forward
// It was need to be calculated
else if(selectionStart - dragging.selectionStart == -1){
// First of all, lets calculate one text line height
let ctx = document.createElement('canvas').getContext('2d');
ctx.font = getComputedStyle(textarea).font;
const measure = ctx.measureText(textarea.value);
const lineHeight = measure.fontBoundingBoxAscent + measure.fontBoundingBoxDescent;
// Then set offset 0 if text moved backward or 2 if forward
if(Math.abs(dragging.dragLayerY - dragging.dropLayerY) > 0.6 * lineHeight){
offset = dragging.dragLayerY < dragging.dropLayerY ? 2 : 0;
}
else {
offset = dragging.dragLayerX < dragging.dropLayerX ? 2 : 0;
}
}
else {
// If the pasted text was inserted somewhere after the deletion,
// we need to add to the offset one character that we just inserted
offset = (captureFlag && (selectionStart > dragging.selectionStart)) ? 1 : 0;
}
// Now let's count the positions where we insert the originally selected text
const newSelectionStart = selectionStart + offset;
const newSelectionEnd = dragging.selectionEnd - dragging.selectionStart +
selectionStart + offset;
// Insert text that was originally selected (still in the dragstart event)
newValue = newValue.substr(0, newSelectionStart) +
dragging.selectionData +
newValue.substr(newSelectionStart);
// Apply the new value
textarea.value = newValue;
// And let's select this area of text like the browser
textarea.setSelectionRange(newSelectionStart, newSelectionEnd, "none");
}
}
}
// Reset the variables when the drag is finished
textarea.ondragend = () => {
dragging = null;
captureFlag = null
};
}
<textarea id="textarea" cols="80" rows="10">
row1w1 row1w2 row1w3 row1w4 row1w5
row2w1 row2w2 row2w3 row2w4 row2w5
row3w1 row3w2 row3w3 row3w4 row3w5
row4w1 row4w2 row4w3 row4w4 row4w5
row5w1 row5w2 row5w3 row5w4 row5w5
row6w1 row6w2 row6w3 row6w4 row6w5
row7w1 row7w2 row7w3 row7w4 row7w5
</textarea>

Form validation for username and Email in java script

I'm trying to validate the value in my name element and email address element.
but the below code is not providing the proper validation and my code is still jumping to my php file with wrongs inputs in it.
can anybody please provide me some guidance on this?
var letters = /^[A-Za-z]+$/;
var mailformat = ^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$;
if( document.addform.First_name.value.match(letters)) {
return true;
}
else {
alert( "Username must have alphabet characters only" );
document.addform.First_name.focus() ;
return false;
}
if( document.addform.email.value.match(mailformat) ) {
return true;
}
else {
alert( "You have entered an invalid email address!" );
document.addform.email.focus() ;
return false;
}
You need to return true if both conditions are met, not just one of them.
function validateFormInput () {
let yourUsernameRegEx = new RegExp(...);
let yourMailRegEx = new RegExp(...);
if (!document.addform.First_name.value.match(yourUsernameRegEx)) {
// Other code here (alerts, popups, etc.) ...
return false;
}
if (!document.addform.email.value.match(yourMailRegEx)) {
// Other code here (alerts, popups, etc.) ...
return false;
}
return true;
}

How to check if a textbox contains a specific string or not?

I have an input textfield named "textbox" and a button named "submit".I also have two text messages "mc_error" and "form_submitted" which are not visible from the beginning. Upon clicking the button, I want it to check if the textfield contains "#" in it. I have tried the below code that uses indexOf but it always returns the value -1 and therefore upon execution always "mc_error" becomes visible.
var str:String = textbox.text;
submit.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
mc_error.visible = false;
form_submitted.visible = false;
function fl_MouseClickHandler(event:MouseEvent):void
{
var index:int = str.indexOf("#");
if(index == -1)
{
mc_error.visible=true;
}
else
{
form_submitted.visible=true;
}
}
Would be grateful if got some immediate answers as i need it working in 2 days.Thanks
Because you set variable before user inputs anything there and it is always "". Just don't use that variable (or read it in the function body as shown below) and it will be fine.
function fl_MouseClickHandler(event:MouseEvent):void
{
var str:String = textbox.text;
var index:int = str.indexOf("#");
if(index == -1)
{
mc_error.visible=true;
}
else
{
form_submitted.visible=true;
}
}

Permutation of Actionscript 3 Array

Greetings,
This is my first post and I hope someone out there can help. I am an educator and I designed a quiz using Actionscript 3 (Adobe Flash) that is to determine all the different ways a family can have three children.
I have two buttons that enter either the letter B (for boy) or G (for girl) into an input text field named text_entry. I then have a submit button named enter_btn that checks to see if the entry into the input text is correct. If the input is correct, the timeline moves to the next problem (frame labeled checkmark); if it is incorrect the timeline moves to the end of the quiz (frame 62).
The following code works well for any particular correct single entry (ie: BGB). I need to write code in which all eight correct variations must be entered, but they can be entered in any order (permutation):
ie:
BBB,BBG,BGB,BGG,GBB,GBG,GGB,GGG; or
BGB,GGG,BBG,BBB,GGB,BGB,GGB,BGG; or
GGB,GGG,BBG,BBB,GGB,BGB,BGB,BGG; etc...
there are over 40,000 ways to enter these eight ways of having three children. Help!
baby_B.addEventListener(MouseEvent.CLICK, letterB);
function letterB(event:MouseEvent)
{
text_entry.appendText("B");
}
baby_G.addEventListener(MouseEvent.CLICK, letterG);
function letterG(event:MouseEvent)
{
text_entry.appendText("G");
}
enter_btn.addEventListener(MouseEvent.CLICK, check);
function check(event:MouseEvent):void {
var solution_S:Array=["BBB","BBG","BGB","BGG","GBB","GBG","GGB","GGG "];
if(solution_S.indexOf(text_entry.text)>=0)
{
gotoAndStop("checkmark");
}
else
{
gotoAndPlay(62);
}
}
If you know the correct code, please write it out for me. Thanks!
You will just need to keep a little bit of state to know what the user has entered so far. One possible way of doing that is to have a custom object/dictionary that you initialize outside all your functions, so that it is preserved during the transitions between frames/runs of the functions:
var solutionEntered:Object = {"BBB":false, "BBG":false, /*fill in rest */ };
Then in your function check you can perform an additional check, something like:
function check(event:MouseEvent):void {
var solution_S:Array=["BBB","BBG","BGB","BGG","GBB","GBG","GGB","GGG "];
if(solution_S.indexOf(text_entry.text)>=0) {
// We know the user entered a valid solution, let's check if
// then entered it before
if(solutionEntered[text_entry.text]) {
// yes they entered it before, do whatever you need to do
} else {
// no they haven't entered it, set the status as entered
solutionEntered[text_entry.text] = true;
}
// continue rest of your function
}
// continue the rest of your function
}
Note that this is not necessarily an optimal solution, but it keeps with the code style you already have.
Try this:
import flash.text.TextField;
import flash.events.MouseEvent;
import flash.display.Sprite;
var correctAnswers : Array = [ "BBB", "BBG", "BGB", "GBB", "BGG", "GGB", "GBG", "GGG" ];
var answersSoFar : Array;
var textField : TextField; //on stage
var submitButton : Sprite; //on stage
var correctAnswerCount : int;
//for testing
textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG";
//textField.text = "BGB,BBB,GGG,BBG,GBB,BGG,GGB,GBG,";
//textField.text = "BBB,BBG, BGB,GBB,BGG, GGB, GBG, GGG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG,BBG";
submitButton.addEventListener( MouseEvent.CLICK, onSubmit );
function onSubmit( event : MouseEvent ) : void
{
var answers : Array = getAnswersArray( textField.text );
answersSoFar = [];
correctAnswerCount = 0;
for each ( var answer : String in answers )
if ( answerIsCorrect( answer ) ) correctAnswerCount++;
if ( correctAnswerCount == correctAnswers.length ) trace( "correct" );
else trace( "incorrect" );
}
function getAnswersArray( string : String ) : Array
{
string = removeInvalidCharacters( string );
return string.split( "," );
}
function removeInvalidCharacters( string : String ) : String
{
var result : String = "";
for ( var i : int, len = string.length; i < len; i++ )
if ( string.charAt( i ) == "B" || string.charAt( i ) == "G" || string.charAt( i ) == "," )
result += string.charAt( i );
return result;
}
function answerIsCorrect( answer : String ) : Boolean
{
if ( answerIsADuplicate( answer ) ) return false;
else answersSoFar.push( answer );
if ( answerIsInListOfCorrectAnswers( answer ) ) return true;
return false;
}
function answerIsInListOfCorrectAnswers( answer : String ) : Boolean
{
if ( correctAnswers.indexOf( answer ) == -1 ) return false;
return true;
}
function answerIsADuplicate( answer : String ) : Boolean
{
if ( answersSoFar.indexOf( answer ) == -1 ) return false;
return true;
}
note that in the original code you pasted, you have an extra space in the last element of your correct answer list - "GGG " should be "GGG"
this works
baby_B.addEventListener(MouseEvent.CLICK, letterB);
function letterB(event:MouseEvent) {
text_entry.appendText("B");
}
baby_G.addEventListener(MouseEvent.CLICK, letterG);
function letterG(event:MouseEvent) {
text_entry.appendText("G");
}
var valid:Array = ["BBB","BBG","BGB","BGG","GBB","GBG","GGB","GGG"];
enter_btn.addEventListener(MouseEvent.CLICK, check);
function check(event:MouseEvent):void {
var parts:Array = text_entry.text.split(/,\s*/g); // split the text into component parts
var dup:Array = valid.slice(); // copy the correct list
while(parts.length){ // run through each answer component
var part:String = parts.pop(); // grab the last one
part = part.replace(/(^\s+|\s+$)/g, ''); // strip leading/trailing white space
var pos:int = dup.indexOf(part); // is it in the list of correct answers?
if(pos != -1){ // if it is...
dup.splice(pos, 1); // then remove that answer from the list
}
}
if(dup.length == 0) { // if it's 0, they got all the correct answers
gotoAndStop("checkmark");
} else { // otherwise, they didn't get one or more correct answers
gotoAndPlay(62);
}
}

Tabbing in text boxes

How can I make a text box that allows users to enter tabs, and does not send the user to the next element when the tab button is pressed?
You only need to check for tabs onkeydown via event.keyCode === 9. Inserting the character into the textarea is non-trivial - use a library or google for 'insertatcaret'.
There are already some plug-ins for jQuery that do this. One for example is Tabby.
<textarea onkeydown="return catchTab(this, event);">
JS code:
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function replaceSelection (input, replaceString) {
if (input.setSelectionRange) {
var selectionStart = input.selectionStart;
var selectionEnd = input.selectionEnd;
input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
if (selectionStart != selectionEnd){
setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
} else{
setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
}
} else if (document.selection) {
var range = document.selection.createRange();
if (range.parentElement() == input) {
var isCollapsed = range.text == '';
range.text = replaceString;
if (!isCollapsed) {
range.moveStart('character', -replaceString.length);
range.select();
}
}
}
}
function catchTab(item,e){
if(navigator.userAgent.match("Gecko")){
c=e.which;
} else{
c=e.keyCode;
}
if(c==9){
replaceSelection(item, "\t");
setTimeout(function() { item.focus() } , 0);
return false;
}
}
You can use JavaScript to catch the tab keypress event and replace it with spaces (I'm not sure about inserting tabs into a textarea).
E: This page looks good.
onkeypress, onkeyup or onkeydown check the key that was pressed and if it is a tab then append \t to the textbox and return false so that focus remains on the textbox
you will most likely have to use textranges so that tabs can be inserted anywhere not at the end of the text
that's the basic idea for the rest google is your friend :)
Do NOT try to capture the onkeypress event for the 'TAB' key in IE (it doesn't work) (bug 249)
Try onkeydown or onkeyup instead.