user3815083
user3815083

Reputation: 33

jQuery - Add comma when press enter key

I have a textarea and i want type keywords into this and want it add comma automatically after press Enter key, for example you type a words or sentence then you press Enter key and it will add comma after each words or .. i write a simple code but it have two problem, first it will add comma everytime you press Enter and it just will add comma after first words but i want it add comma after each words not just one. second problem is i dont want it goes to new line when you press Enter.

$('#formID').live("keypress", function(e){
if (e.keyCode == 13) {
  $("textarea").each(function() {
    $(this).val($(this).val().replace(/ /g, " ، "));
  });
}
});

JSFiddle

Upvotes: 1

Views: 1712

Answers (2)

Mahesh Thorat
Mahesh Thorat

Reputation: 1

 $('textarea').keypress(function(e){
    if (e.keyCode == 13) {
     e.preventDefault();
     $(this).val($(this).val() + ' , ')
   }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id=formID><textarea></textarea><input type=submit></form>

Upvotes: 0

jpcanamaque
jpcanamaque

Reputation: 1069

Try this:

$('textarea').keypress(function(e){
if (e.keyCode == 13) {
    // alert($('textarea').val());
    $('textarea').val($('textarea').val() + ', ');
}
});

Upvotes: 1

Related Questions