views:

46

answers:

4

hi guys i have a html form where i have a textfield which 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.

A: 

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);
});
MarvinLabs
what if user selects the text and deletes it through mouse.
sushil bharwani
@MarvinLabs: your solution will not work if the content is pasted in the textbox and not written from keyboard. Because in that case `keyup` event will not fire.
Alpesh
In that case, the change() event could be what you need, I had forgotten the case of copy/paste, sorry.
MarvinLabs
A: 

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?

Nev Stokes
ya thanks.. But thats what not desired. And already given thought.
sushil bharwani
A: 

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 =]

madeinstefano
How i didnt followed...
sushil bharwani
+1  A: 

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">
mplungjan