Tony Evyght
Tony Evyght

Reputation: 2575

Non repeat comma

<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />

$('.dot').keydown(function(){
        $(this).val($(this).val().toString().replace(/\./g, ','));
})

http://jsfiddle.net/ZtkBW/

In this example i replace dot to comma. How can i block the addition of two commas in current input?

If in input is already one comma then next should be remove.

Upvotes: 1

Views: 209

Answers (4)

Engineer
Engineer

Reputation: 48793

$('.dot').keypress(function(e){
     if( ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) && 
         (e.charCode==','.charCodeAt(0) || e.charCode=='.'.charCodeAt(0)) )
         e.preventDefault();
     else
         $(this).val($(this).val().toString().replace(/\./g, ','));
})​;​

DEMO

Upvotes: 1

Guffa
Guffa

Reputation: 700292

Use the keypress event instead of the keydown event (as keydown isn't triggered by key repeat).

Look for the . and , characters, and stop the event by returning false if there already is a comma in the text.

As the event is stoppable, it occurs before the value is changed, so you need to use a timeout for replacing the period with a comma.

$('.dot').keypress(function(e){
    var txt = $(this).val();
    if (e.which == 46) {
        if (txt.indexOf(',') != -1) {
            return false;
        } else {
            var t = $(this);
            window.setTimeout(function(){
                t.val(t.val().replace('.', ','));
            }, 0);
        }
    } else if (e.which == 44) {
      return txt.indexOf(',') == -1;
    }
});

Demo: http://jsfiddle.net/eAkUc/1/

Upvotes: 2

Jon Grant
Jon Grant

Reputation: 11530

This is a classic case of trying to solving a problem with regular expressions, and now you have two problems...

It's not clear exactly what you want, but this will stop multiple presses of the comma key. It should be a short step from here to detect the period (code 190) and do whatever you want with it instead.

$('.dot').keydown(function(e){
    if (e.which == 188) {
        if (this.value.indexOf(',') != -1) {
            e.preventDefault();
            return false;
        }
    }
})​;

Upvotes: 4

Elliot Bonneville
Elliot Bonneville

Reputation: 53301

If I understand what you want correctly, here's one way of doing it:

var myVal = $(this).val();
myVal[myVal.indexOf(",")] = ".";
myVal.split(",").join("");
$(this).val(myVal);

Upvotes: 0

Related Questions