Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <input type="text" id="nameId" onkeydown="validate(this.val)"/>
- function validate2(val) {
- // have no idea how to do.
- }
- $("#nameId").on("keydown", function(e) {
- // if user writes a char at index == 0 that is not an arrow or HOME and END
- if (($(this).get(0).selectionStart == 0 && (e.keyCode < 35 || e.keyCode > 40))
- // or if user tries to erase first char
- || ($(this).get(0).selectionStart == 1 && e.keyCode == 8)) {
- // don't write the character
- return false;
- }
- });
- // prevent right click
- $("#nameId").bind("contextmenu", function(e) {
- e.preventDefault();
- });
- <input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
- function restore(el,event) {
- if(el.value.length == 0){
- el.value = el.dataset.value.substr(0,1);
- }else{
- el.dataset.value = el.value;
- }
- }
- function save(el,event) {
- var key = event.which || event.charCode || event.keyCode;
- if((key === 8 && el.value.length === 1)
- || (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
- event.preventDefault();
- }
- if(el.value.length > 0){
- el.dataset.value = el.value;
- }
- }
- <input type="text" id="nameId" value="Given Name" />
- var lastentry = '';
- $("#nameId").on("keyup", function(e) {
- var targetValue = $(e.currentTarget).attr('value');
- var targetValueLength = targetValue.length;
- var inputValue = this.value;
- if(checkChanges(targetValueLength, targetValue, inputValue))
- this.value = targetValue + lastentry;
- else
- lastentry = this.value.slice(targetValueLength)
- });
- function checkChanges(targetValueLength, targetValue, inputValue)
- {
- for(var i = 0; i < targetValueLength ; i++)
- {
- if(targetValue[i] != inputValue[i])
- return true;
- }
- return false;
- }
- <input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
- <script>
- function validate(val,event) {
- // have no idea how to do.
- if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
- var startPos = event.target.selectionStart,
- endPos = event.target.selectionEnd;
- console.log(startPos,endPos);
- if(startPos === 0 && startPos != endPos){
- var restPart = val.slice(endPos,val.length);
- if(restPart){
- val = val[0].concat(restPart);
- } else{
- val = val[0]
- }
- event.target.value = val;
- event.preventDefault();
- } else if(startPos === 0 && startPos === endPos && event.which === 46){
- event.preventDefault();
- } else if(startPos === 1 && event.which === 8){
- event.preventDefault();
- }
- }
- }
- </script>
- $(document).keydown(function(e)
- {
- var value = $('#nameId').val().length;
- if ( e.keyCode == 8 && value < 2)
- e.preventDefault();
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement