Question on tabbing to next NON-READONLY field - javascript

On blur of field1, field2 is set to READONLY but the cursor on my page then defaults to field2 and the cursor is located at the END of the value and when the user clicks the backspace button the value can be erased. I would like the ability to have the cursor move to the next NON-READONLY or ENABLED field on the page. Is that do-able with jQuery?
Any help/direction would be appreciated.
Here is my code:
$(function() {
$("#ARTransferForm\\:fromAccountAmt").blur(function() {
var origAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
var fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
// Call validation "r2" function
var modFromAccountAmount = r2(fromAccountAmount);
//alert("modFromAccountAmount = " + modFromAccountAmount);
fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val(modFromAccountAmount).val();
//alert ("modified fromAccountAmount = " + fromAccountAmount);
if (modFromAccountAmount != "N.aN") {
var firstChar = fromAccountAmount.charAt(0);
var fromAcctAmtLen = $("#ARTransferForm\\:fromAccountAmt").val().length;
if (firstChar == "-") {
var revFromAcctAmt = fromAccountAmount.substring(1, fromAcctAmtLen);
$("#ARTransferForm\\:toAccountAmt").val(revFromAcctAmt);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
} else {
$("#ARTransferForm\\:toAccountAmt").val("-"+fromAccountAmount);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
}
} else {
$("#ARTransferForm\\:fromAccountAmt").val(origAccountAmount);
$("#ARTransferForm\\:fromAccountAmt").select();
alert("Invalid From Amount Format. Use ##.## (NO commas or $ sign)");
}
});
});

Have you tried modifying tabindexes onblur, before RETURN TRUE, to control where the cursor goes? It's kind of a hack, but there you go.
Also, you could use a delegated event (perhaps on the form) to intercept and return false on any keypress events that would modify the value of any readonly input. Something like:
$('#ARTransferForm *[readonly]').live("keypress", function(event) {
// compare keycode to blacklist: backspace, perhaps delete too?
if(bKeyIsBlacklisted) {
event.preventDefault();
return false;
}
});
(Note: that is pretty pseudocodeonous. You'll want to double-check the syntax for sizzle's attribute selectors, as well as jquery's event delegation signature. And be real careful about how wide you cast your "no keys" net: try to avoid disallowing Copy and other operations performed with keyboard shortcuts. You will need to check for a modifier key to distinguish between the user trying to type "c" and Ctrl+C.
Which browser(s) are you testing this in?

Related

Prevent From Writing on TextArea using Bind Event "input propertychange"

I am handling the content inside a textarea using binding a function to the event "input propertychange"
Like this:
$('#textarea').bind('input propertychange', function () {
var textarea = document.getElementById('textarea');
window.lastLineWriting = textarea.value.substr(0, textarea.value.length).split("\n").length;
var writingOnLine = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
if (writingOnLine < window.lastLineWriting) {
//dont write on textarea
}
});
I don't know how to prevent the char typed by the user's keyboard to appear on the textarea... Inside that if I want to prevent the text to be inserted on textarea..
How can I do this?
you could easily stop the user from typing with this code, using jQuery:
$('textarea').bind('keypress', function (e) {
e.preventDefault();
return false;
});
NOTE:
this code will prevent the user from typing in all the textareas, to bind it specifically to one or some selected elements, you must change the selector to the desired elements.
var editable = false // Your Condition
if(editable != "true"){
$("#textarea" ).attr("disabled",true);
}

Mirroring input content with non-printable chars like CTRL, ALT or shift key

When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code

Detect when text is entered into the textarea and change it correspondingly

I have a textarea where users can enter or paste email addresses of other people and send them an invite after pressing Submit button. Each email must be seperated with a comma and valid before the form is submitted - validation is taken care of by jQuery Validate plugin & multiemail method.
Problem
Some people paste email addresses directly from their email clients and those emails are often in a weird format - containing name and surname before the actual email, or the email is wrapped in < >. For example:
"The Dude" <the.dude#gmail.com>, "The Dudette" <thedudette193#gmail.com>
Question
What I want to do is to Extract all email addresses from bulk text using jquery, but I'm having problems integrating this piece of code to work with my textarea - I don't know where to start.
How could I use the code from the above answer to extract each email entered into the textarea after a comma is typed or when the focus is moved away from textarea? So if I paste "The Dude" <the.dude#gmail.com> and type , after it or switch focus away, the entered value would change to the.dude#gmail.com.
I'm guessing something like this :
var textarea = $('#emails');
textarea.on({
keyup: function(e) {
if (e.which === 188) check();
},
blur: check
});
function check() {
var val = $.trim(textarea.val()),
err = '';
if (!val.length) {
err = 'No input ?';
return;
}
var emails = val.split(','),
notvalid = [],
temp = [];
$.each(emails, function(_,mail) {
mail = $.trim(mail);
if ( mail.length ) {
var m = mail.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (m) {
temp.push(m);
}else{
temp.push(mail);
notvalid.push(mail)
}
}else{
temp.push(mail);
}
if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', ');
});
$('#error').html(err);
textarea.val((temp.length ? temp : emails).join(', '));
}
FIDDLE
you can detect when an textarea is changed (or other input field) by using an eventhandler. Jquery supports multiple events (have a look here http://api.jquery.com/category/events/). In this particular case I should use the keyup event for triggering the extractEmails function. This way your extraction will be "live". However, it is also possible by catching a blur or change event.
With keyup eventhandler
http://jsfiddle.net/kasperfish/9hLtW/5/
$('#text').on('keyup',function(event) {
emails=extractEmails($(this).val());
$("#emails").text(emails);
});
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
This will convert the entered text to emails when you either lose focus, or enter a comma, as you requested:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emailtext").on('keypress blur', function(e) {
if (e.which === 44 || e.type =="blur")
{
$('#emails').text(extractEmails($("#emailtext").val()));
}
});
Here's the fiddle:
http://jsfiddle.net/Mj2KM/

jQuery keydown event: Value coming delayed

I have following issue:
I got an event listener on an input field. On every keydown event the value of the input field should get validated. The problem is that the value assigned to the event-target is delayed:
You have an empty input field and type down one letter:
$('form.registration').keydown(function(e) {
var $el = $(e.target);
if ($el.val() == "") {
$el.closest("div.control-group").addClass("error");
}
console.log($el.val()); // this logs ""
});
You type in the second letter
$('form.registration').keydown(function(e) {
var $el = $(e.target);
if ($el.val() == "") {
$el.closest("div.control-group").addClass("error");
}
console.log($el.val()); // this logs the first letter (for example: "a")
});
As you see the value is always delayed by one letter.
How can I fix this?
I will suggest you use keyup instead. This will prevent your program running intensively when user presses the key and holds it, the content is being processed only after user releases the key. This method is very convenient in many cases.

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.

Categories