0

I have following code :-

/*****html*********/
<input type="text" id="firstname">
/******jquery********/
$(document).ready(function(){
 $("#firstname").keyup(function(){
 var text=$(this).val();
 $(this).val(text.replace(/[^\s((a-zA-Z))]/g,''));
 });
});

I don't want any whitespace in my input box.Tried above code but not working. Something wrong in my code. Please help.

asked Jun 16, 2017 at 10:37

4 Answers 4

2
$('#firstname').keypress(function( e ) {
 if(e.which === 32) 
 return false;
})​​​​​;​

You can prevent key press if white space. So that no one can type it.

answered Jun 16, 2017 at 10:41
Sign up to request clarification or add additional context in comments.

3 Comments

This is false in case user copy pastes the text though. Ref:- stackoverflow.com/questions/18608954/…
And what happens if the user paste the code in input ?
@AndreiTodorut you are right. then this code will not work.
2

Your regex is wrong. Please check this https://jsfiddle.net/w1uqqsc3/

$(this).val(text.replace(/[\s((0-9))]/g,''));

Use this app for regex http://regexr.com/

There you can find references about regex.

answered Jun 16, 2017 at 10:45

Comments

0

Worked for me

$("#firstname").keyup(function(){
 var text=$(this).val();
 $(this).val(text.replace(/[^(a-zA-Z)]/g,''));
});
answered Jun 16, 2017 at 11:00

Comments

0

If you try to do replacement during keyup event, you might face cursor jump issues while trying to edit the text.

I would prefer to allow them typing whatever they want and clean-up the text during change event as below (This would work perfectly for copy-paste scenario too):

$(document).ready(function(){
 $("#firstname").change(function(){
 var text=$(this).val();
 $(this).val(text.replace(/\s/g,''));
 });
});

JS Fiddle: https://jsfiddle.net/pnaveen/w1uqqsc3/2/

answered Jun 16, 2017 at 12:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.