pc_oc
pc_oc

Reputation: 545

not receive negative numbers

I have the following code: http://jsfiddle.net/ntywf/1987/

$(document).ready(function () {    
    $('input').keyup(function() {
        var $th = $(this);
        $th.val($th.val().replace(/[-]/g, function(str) { 
            //alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); 
            return ''; 
        }));
    });
});

what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)

Upvotes: 1

Views: 146

Answers (4)

Pralhad Narsinh Sonar
Pralhad Narsinh Sonar

Reputation: 1454

Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.

<input type="number" min="0"/>

JSFIDDLE DEMO will be helpful to you.

Upvotes: 0

CesarMiguel
CesarMiguel

Reputation: 3830

You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:

$('input').keyup(function(e) {
        
    var code = e.keyCode || e.which;
    if(code == 109 || code == 189) { //Enter keycode
       //Do something
        var valor = $(this).val();
        $(this).val(valor.replace(/[-]/g, ''))
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>

Upvotes: 1

dreamweiver
dreamweiver

Reputation: 6002

This should solve your problem

What I have done is:

  • I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)

MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

JS Code:

$(document).ready(function () {    
  $('input').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[-]/g, function(str) { 
        //alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); 
        return ''; 
    } ) );
    $('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
  });
});

JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/

Upvotes: 0

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Here what I have tried.

JS

$('input').keyup(function() {
        var $th = $(this).val();
        $th = $th.replace(/[-]/g, "");
        $(this).val($th)
        console.log( $(this).val());
    });

It will remove - sign from data.

Upvotes: 0

Related Questions