Brainmaniac
Brainmaniac

Reputation: 2556

change spaces entered in input field to underscore in real time

I have an input field that should switch all spaces entered to a '_' in real time. Meaning when the user hits the spacebar in that input field a underscore is being displayed instead of a space. I am quite new to javascript/jquery so please don't judge my setTimeout-n00bidity to hard:

$( "#inputId" ).keydown(function (key){
    var code = key.keyCode || key.which;
    if( code == 32 ) { //Space key code
        $( this ).val(
            function( index, value ){
                return value.substr( 0, value.length - 1 );
        })
        setTimeout(
            function(){
                $(this).val($(this).val() + "_");
            }, 10
        )
    }
})

Upvotes: 1

Views: 2503

Answers (5)

Shiv Kumar Baghel
Shiv Kumar Baghel

Reputation: 2480

$( "#inputId" ).keyup(function (key){
    var code = key.keyCode || key.which;
    if( code == 32 ) { //Space key code        
       $(this).val($(this).val().replace(/ /g,"_"));
    }
});

Upvotes: 0

com
com

Reputation: 395

No jQuery, simple solution:

var input = document.getElementById("inputId");

input.oninput = function (e) {
  e.target.value = e.target.value.replace(' ', '_');
}
<input type="text" id="inputId" />

Upvotes: 4

Barmar
Barmar

Reputation: 782064

Use the keyup event rather than keydown, and simply replace all spaces with _. The keyup event runs after the value has been modified based on what the user typed, so you don't need to check the charCode.

$("#inputId").keyup(function() {
    $(this).val(function(i, oldval) {
        return oldval.replace(/ /g, '_');
    });
});

Upvotes: 1

HoangHieu
HoangHieu

Reputation: 2840

You can use Change value of key board input ex:

<div>
    <label>Test:</label>
    <input type="text" id="test">
</div>

$("#test").on("keypress", function (e) {
    if (32 == e.keyCode) {
        e.preventDefault();
        var newString = $("#test").val() + "_";
        $("#test").val(newString);
    }
});

Related: jQuery: Change keyboard value when input

Upvotes: 0

31piy
31piy

Reputation: 23859

You may listen to the input event and then replace the spaces with underscores in the listener. This way, you don't need to have a timeout.

$("#inputId").on('input', function(key) {
  var value = $(this).val();
  $(this).val(value.replace(/ /g, '_'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputId">

Upvotes: 5

Related Questions