2

I'm trying to use Javascript to make a textbox that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. I need to allow only 10 digit numeric after the readonly text and need to validate for the numeric digits. The following is the Javascript code for having the readonly in textbox

var readOnlyLength = $('#field').val().length;
 $('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
    && ((this.selectionStart < readOnlyLength)
    || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
}
});       
5
  • you can reach read only by making the input disabled. Commented Sep 21, 2015 at 6:20
  • 2
    Why not simply go for using label for the fixed text and text-box for the numeric input? Commented Sep 21, 2015 at 6:30
  • allow only 10 digit numeric is that fixed 10 or max 10 ? Commented Sep 21, 2015 at 6:37
  • 1
    You should be looking for stackoverflow.com/questions/15181417/… Commented Sep 21, 2015 at 7:02
  • What's the question? Commented Sep 21, 2015 at 7:20

1 Answer 1

1

If you looking for solution with script then here is plain js and RegExp:

var fixedText = function(textbox, label) {
  var num = textbox.value.replace(/\D/g, ''); //non numeric
  num = num.substr(0, 10); //max 10 digits
  textbox.value = label + num;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />

With simple label ,input and script:

var numeric = function(textbox) {
  var num = textbox.value.replace(/\D/g, '');
  num = num.substr(0, 10);
  textbox.value = num;
};
label.partial,
input.partial {
  border: 1px ridge grey;
  margin-bottom: 3px;
}
label.partial {
  border-right: none;
  cursor: text;
}
input.partial {
  border-left: none;
  margin-left: -4px;
  top: -1px;
  position: relative;
}
<label for="PostalCode" class='partial'>Postal Code&nbsp;</label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No&nbsp;</label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.