TamoDaleko
TamoDaleko

Reputation: 151

Javascript removes value of input field

I want to check when a user types "," or "." then remove the "." or the "," and replace it with :00

for example user types 2.5 the result should be 2:00

So far nothing special but somehow my hole input field is getting cleared just the new value :00 is there

    if($('#enterTime').val().indexOf("." || ",") !=-1){
        $('#enterTime').val($('#enterTime').val().replace(/./g, ""));
        $('#enterTime').val($('#enterTime').val().replace(/,/g, ""));
        $('#enterTime').val($('#enterTime').val() + ':00');
}

Upvotes: 3

Views: 68

Answers (3)

J Santosh
J Santosh

Reputation: 3847

Try this

Update();
function Update() {
    var value = $('#enterTime').val();
    value = value.replace(/(\..*|\,.*)/g, ":00")
    $('#text3').text(value)
}

$('#enterTime').keyup(function () {
    Update();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='enterTime' value='2.00500'> <span id="text3"></span>

Upvotes: 1

Manwal
Manwal

Reputation: 23816

Escape special character with \ while using in regex

$('#enterTime').val($('#enterTime').val().replace(/\./g, ":00"));
$('#enterTime').val($('#enterTime').val().replace(/\,/g, ":00"));

DEMO

Using || in indexOf is incorrect. use follwing

if($('#enterTime').val().indexOf(".") !=-1 || $('#enterTime').val().indexOf(",") !=-1){
    $('#enterTime').val($('#enterTime').val().replace(/\./g, ":00"));
    $('#enterTime').val($('#enterTime').val().replace(/\,/g, ":00"));
}

Upvotes: 0

somethinghere
somethinghere

Reputation: 17340

The . in regex means 'Any character except newline', so simply escape it using a backslash:

/\./g

You could really simplify this by doing:

var time = $('#enterTime');
time.val(time.val().replace(/(\.|\,)/g, ":00"));

In this case I have added the | to say 'either , or .', making your regex match both. I added the () to encapsulate it.

Here's a (unrelated) implementation of the regex:

var text = document.getElementById('text');
text.textContent = text.textContent.replace(/(\.|\,)/g, ":00");

var text = document.getElementById('text2');
text.textContent = text.textContent.replace(/(\.|\,)/g, ":00");
<p>The original text was: 2,</p>
<div id="text">2,</div>

<p>The original text was: 2.</p>
<div id="text2">2.</div>

Upvotes: 6

Related Questions