user3144577
user3144577

Reputation: 19

Regular Expression is not working using onkeyup function

$(function(){
    $('#addAction').click(function(){
        count += 1;
        $('#extras').append('<div class="row"><div class="col-md-1">Delivery Fee: </div><input id="price_' + count + '" name="prices[]' + '" type="text" onkeyup="javascript:this.value=this.value.replace(/[^0-9.]/g, \'\');" /></div>' );
    });
});

I don't know why regular expression is not replacing the value by empty string. if someone want to add alphabet value in numeric field, then alphabet value should be remove from numeric field, but I tried, it is not working, kindly tell me the proper solution.

Upvotes: 0

Views: 890

Answers (2)

user4639281
user4639281

Reputation:

I'm not quite sure what that regex is supposed to do, but I am assuming that you're trying to only allow numbers in the input field. A better way to do this is to check the Event.keyCode property and use Event.preventDefault() to disallow any non-numeric characters.

You should refrain from using inline JavaScript, it is not maintainable and will lead to issues later on.

You can use apply the onkeyup event listener using jQuery.keyup in this situation.

$(function(){
    var count = 0;
    $('#addAction').click(function(){
        count += 1;
        var newRow = $('<div class="row"><div class="col-md-1">Delivery Fee: </div><input id="price_' + count + '" name="prices[]' + '" type="text"></div>');
        $('#price_' + count, newRow).keydown(function(event){
            var charCode = event.keyCode;
            if (!(charCode >= 48 && charCode <= 57) 
             && !(charCode >= 96 && charCode <= 105)) {
                event.preventDefault();
            }
        });
        $('#extras').append(newRow);
    });
});
<button id="addAction">Click Me</button>
<div id="extras"></div>

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

just95
just95

Reputation: 1099

javascript: is only needed for the href attribute of anchor elements.

<input type="text" onkeyup="this.value=this.value.replace(/[^0-9.]/g, '');" />

Upvotes: 2

Related Questions