Prevent typing spaces in an HTML text box with jQuery - javascript

So I've got an HTML form that users can type in. How can I use javascript/jQuery to immediately and seamlessly remove spaces from a text box when one is put in? I've been researching the .val() jQuery method and came up with this:
$('input').keydown(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});
That does weird things to removing text and the spaces still show up on keystroke, they just get removed on the following keystroke. Any suggestions?

You could prevent it from being added at all by checking whether the key pressed is the space bar and returning false if so:
​$("input").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
Here's a working example.

Try use keyup
Live Demo
$('input').keyup(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});

Related

How to clear a textarea value in jQuery?

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);
When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.
Change noteNumberInput.addEventListener("keydown", validate); to use keyup
Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO
Your only asking for the validate() function to actually execute when you've pressed the next key.
I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...

tab key is not working as expected when using jquery change event

I had some weird result from jquery events, though I am not fully convinced whether it is a jquery issue. I hope some jquery geeks can answer this.
I had the following code snippet in my html page, to change the focus to the second input box once user enter a string of length 9 in first input box. This auto-focusing is working smoothly. But when I press tab from first input box, it is always skipping the second input box and goes to the next html element to second input box.
$("input.first").change(function (e){
var text = $(this).val();
if (text.length == 9){
$("input[id='second']").focus();
}
});
I tried putting tabindex property to html elements still it continued its misbehavior. But at the end when I changed change event to keypress event tab key started to flow as expected.
Is there anyone who could explain why this happens? Thanks for any answers.
you can add tab index to controls manually. I hope it will work.
$(function() {
var tabindex = 1;
$('input').each(function() {
if (this.type != "hidden") {
var $input = $(this);
$input.attr("tabindex", tabindex);
tabindex++;
}
});
});

How can I set the focus to the next field (based on tabindex) using JavaScript? [duplicate]

In jQuery, how can I trigger the behavior of a user tabbing to the next input field?
I've tried this:
var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);
But triggering the event doesn't move the cursor to the next field.
I suppose I could move the cursor manually using focus(), but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.
Any ideas?
Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
$.fn.focusNextInputField = function() {
return this.each(function() {
var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
});
};
The use is as follows:
$( 'current_field_selector' ).focusNextInputField();
See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup event, and check the entered number of characters.
The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus event on the element with that index.
There's a JQuery plugin available:
http://www.mathachew.com/sandbox/jquery-autotab/
Have you tried using
$("input").trigger( 'keypress', e );
as a solution?
I find sometimes being explicit is best.
If that doesn't work possibly even
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );.
Hope this helps.

jQuery Keyboard Function keyPress

I have the following HTML/CSS to create a simple keyboard. I have tried experimenting with jQuery keyPress(), yet I can't seem to get it so while you are pressing a key on the keyboard, the corresponding letter has the class 'trigger'.
For example, when you press Q in the textarea with id 'input', the span with id 'q' should change its background to the color green (to the class 'trigger')
Any help would be much appreciated, thanks in advance.
EDIT
So far I have some Javascript, that alerts on each keystroke. See this example
If you want the background to change only while the key is down you need to set it on keydown and set it back on keyup:
$(function () {
$("#input").keydown(function (event) {
$("#" + String.fromCharCode(event.which)).addClass("trigger");
}).keyup(function (event) {
$("#" + String.fromCharCode(event.which)).removeClass("trigger");
});
});
Note that keydown and keyup return key codes not character codes, but as far as the alphabet keys go it is safe to treat them as if they were character codes for the uppercase letters. (So in the following demo I've changed the ids of the spans to be uppercase to save doing arithmetic in the event handlers.)
Demo: http://jsfiddle.net/AHPaY/6/
P.S. If you experiment with the demo you'll see this works for simultaneous keypresses too, e.g., hold down Q and T at the same time...
On the keypress event, the event.which property maps to a character code. The String.fromCharCode method can be used to convert the numeric charcode to a character.
In the example, a regular expression is used to check whether the single character is a valid code. If yes, then a class is added.
Demo: http://jsfiddle.net/AHPaY/4/
$(function () {
$("#input").keypress(function (event) {
$('.trigger').removeClass('trigger');
var char = String.fromCharCode(event.which).toLowerCase();
if (/[qwerty]/.test(char)) {
$('#'+char).addClass('trigger')
}
});
});
Try this
$(function () {
$("#input").keypress(function (event) {
var keycode=event.which || event.keycode;
var key=String.fromCharCode(keycode).toLowerCase();
$('span.trigger').removeClass('trigger').addClass('key'); // reset
$("#"+key).removeClass('key').addClass('trigger');
});
});
A fiddle is here.
Another fiddle is here.
If you want to leave all the spans green then disable the line commented with reset.

Javascript to make input field in edit mode(insert mode)

How is it possible to make a input field editable in javascript. I mean onFocus putting it in insert mode so that values can be overwritten. Any suggestions ???
This should work in modern browsers (also on mobile):
var input = document.querySelector('input'); // or a textarea
input.addEventListener('keypress', function(){
var s = this.selectionStart;
this.value = this.value.substr(0, s) + this.value.substr(s + 1);
this.selectionEnd = s;
}, false);
jsfiddle
Note: This is a basic form of insert functionality so some default functionality like CTRL+Z may break.
After doing some googling, this seems to be related. It might be working trying the play with the following code a bit, but it might only work in specific browsers on specific operating systems, but it's worth a shot anyway.
document.execCommand('OverWrite', false, true);
document.execCommand('OverWrite', false, false);
As per your request, I would say the implementation would work something like this:
<input type="text"
onFocus="document.execCommand('OverWrite', false, true);"
onBlur="document.execCommand('OverWrite', false, false);">
EDIT: May be totally off-topic, depending on the meaning behind the question.
If you can use jQuery, Jeditable is a nice plugin to do just that.
If you must roll your own code, take a look at how that plugin works and use it as a starting point.
Basically, the steps are:
onFocus/onClick - swap your field with an input.
When the user is "done" (hit Enter, click a button), push the result back to the server via Ajax.
When your request completes, update the interface with the new value, hiding the input.
You can try to mimic Insert mode by rewriting the input value on keyup :
var input = $('input'); // your input element
Event.observe(input, 'keydown', function(e) { // event handler
input._lastvalue = input.value;
});
Event.observe(input, 'keyup', function(e) { // event handler
if(input.value == input._lastvalue) return;
if(input.value.length <= input._lastvalue.length) return;
var caretPos = doGetCaretPosition(input);
input.value = input.value.slice(0,caretPos) + input.value.slice(caretPos+1);
doSetCaretPosition(input, caretPos);
});
Here is a demo : http://jsfiddle.net/z6khW/

Categories

Resources