简体   繁体   中英

Format Input Type Text without changing the Value

Is it possible to format the text value of an Input element without actually changing the value itself. For example, if I am entering an id number of the following format:

19801010-1234

I wish the value to be 198010101234 but when more than 8 characters are entered, the hyphen should be displayed. I'm using javascript and nodejs.

This is what I currently have:

HTML

<input id="ssn"
       className= {styles.input}
       type="input"
       value= {this.format(personalNumber)}
       placeholder={translations.personalNumber}
       onChange={this.onChange} />

JS

format(value){
    if(value && value.length>8)
        return value.slice(0, 8) + " - " + value.slice(8);
    return value;
}

I'm using react and the above will of course change the value itself to include a hyphen which I'm hoping I can avoid.

Try this:

<input type="text" id="num"> <span></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    function formatVal(num) {
        num.length == 8 ? $('#num').val(num+'-') : '';
    };

    function origVal(num) {
        $('span').html(num.replace('-', ''));
    }

    $('#num').keypress(function() {
        formatVal($(this).val());
        origVal($('#num').val());
    });
</script>

Might not be the best solution. But it works

jsfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM