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
2010-10-29 11:34:32
what if user selects the text and deletes it through mouse.
sushil bharwani
2010-10-29 11:38:42
@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
2010-10-29 11:39:12
In that case, the change() event could be what you need, I had forgotten the case of copy/paste, sorry.
MarvinLabs
2010-10-29 12:34:11
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
2010-10-29 11:44:58
ya thanks.. But thats what not desired. And already given thought.
sushil bharwani
2010-10-29 12:34:02
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
2010-10-29 11:50:29
+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
2010-10-29 13:58:20