Skip to content

Instantly share code, notes, and snippets.

@meetajhu
Created July 12, 2018 07:59
Show Gist options
  • Save meetajhu/b90af4c84255a063b069ced073844778 to your computer and use it in GitHub Desktop.
Save meetajhu/b90af4c84255a063b069ced073844778 to your computer and use it in GitHub Desktop.
Auto Fill input field when typed without losing cursor position - HTML, Javascript & Jquery
<!DOCTYPE html>
<html>
<head>
<title>Input Fill</title>
</head>
<body>
<input placeholder="Company name option" id="company_name_valid" type="text">
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
/* Input Field AUto fill Pvt Limited */
var $dynamicfield = $('#company_name_valid');
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
$dynamicfield.keyup(function(){
var getnewval = $dynamicfield.val();
var getfieldlength = $dynamicfield.val().length;
if(getfieldlength == 1){
var getcursorposition = document.getElementById('company_name_valid').selectionEnd;
$dynamicfield.val(getnewval+" Private Limited");
setCaretPosition("company_name_valid", getcursorposition);
}
});
document.getElementById('company_name_valid').addEventListener("keydown", KeyCheck);
function KeyCheck(event)
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8: //backspace
var getnewval = $dynamicfield.val();
var getfieldlength = $dynamicfield.val().length;
if(getfieldlength < 18){
var ele = document.getElementById('company_name_valid');
var text = ele.value;
text = text.slice(0, 1);
ele.value = text;
}
break;
case 46: //delete
var getnewval = $dynamicfield.val();
var getfieldlength = $dynamicfield.val().length;
if(getfieldlength < 18){
var ele = document.getElementById('company_name_valid');
var text = ele.value;
text = text.slice(0, 1);
ele.value = text;
}
break;
default:
break;
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment