开发者

always want to keep first digit of my textfield as 0

开发者 https://www.devze.com 2023-01-22 18:47 出处:网络
hi guys i have a html form where i have a textfield whic开发者_JAVA技巧h is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows

hi guys i have a html form where i have a textfield whic开发者_JAVA技巧h is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.


Here is another way. the onKeyUp might not be how you want it to work but at least you have some ideas

<script>
window.onload=function() {
  document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1" 
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">


You can use the event "keyup" triggered when the user enters text in the field:

$('#my-input').keyup(function() {
    var theInputValue = $(this).val();
    // Do whatever you want with the value (like check its length, 
    // append 0 at the beginning, tell the user not to change first
    // character
    //

    // Set the real value
    $(this).val(newValue);
});


You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?


I wrote and tested this code, and works exactly as you expect:

$(function (){
  $('#input_id').bind('input',function (){
    var val = $(this).val();
    var r = val.match(/^[0][0-9]$/g);
    if (r !== null){
      val = r[0];
      if (val.length === 1){
        val = '0' + val;
      }
    }else{
      val = '0';
    }
    $(this).val(val);
  });
});

And works for copy/paste too =]

0

精彩评论

暂无评论...
验证码 换一张
取 消