swapmeet_Lou
swapmeet_Lou

Reputation: 292

Add comma to text box after space bar is pressed

I have value(s) I retrieve via an Ajax request when a page loads. I present them in a text box for a user to adjust. Remove or add. I need to add a comma after the last char, but only after the space bar is pressed.

I have found some similar questions, but none address this specific issue. I've not found a duplicate question.

I've been tinkering with this small piece of code, but it limits me. I cannot backspace and delete, and it will not accept anything under two chars.

$('#symText').keyup(function(){
  var sym = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
  if (sym!=this.value) this.value = sym; 
});

Seeking an alternative that only adds a comma after the last char when the space bar is pressed. Your help is always greatly appreciated.

          $.ajax({
                url: '/Trucking/GetSubSymbols',
                type: 'POST',
                contentType: 'application/json',
                data: sendData,
                success: function (data) {
                    console.log(data);

                    var s = '';
                    for (var i = 0; i < data.length; i++) {
                        s += data[i] + ',';
                    }
                    $(".fillSym").val(s);

                },
                error: function () {
                    //alert('Error');
                    console.log('Error');
                }
            });

PIC of the tb enter image description here

Upvotes: 0

Views: 984

Answers (1)

Salikh Gurgenidze
Salikh Gurgenidze

Reputation: 634

Check it here let me know if its what you want )

$('input[name="numbers"]').on('keyup',function(e){
  if(e.which === 32){
    var str = $(this).val().split('');
    if(str[str.length - 2] === ','){
      $(this).val($(this).val().replace(' ',''));
    }
    $(this).val($(this).val().replace(' ',','));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="numbers" value="61,62,63"/>

Upvotes: 1

Related Questions