1

I need to check the length of the text in a text box that has MaxLength set to 10. If someone pastes more than 10 characters the pasted text is trimmed to 10 characters. How can I detect if the pasted text was longer than 10 characters and let the user know 'your text has been trimmed'?

Also, if when someone pastes I put up an alert box, it triggers the onblur event, which occurs first. How can I prevent this?

<input type="text" id="txt" maxlength="10" onblur="checklength(event);" onpaste="pasted(this)">

function checklength(e)
{
alert('blurry ' + document.getElementById('txt').value.length);
e.cancelBubble=true;
}

function pasted(element) {
setTimeout(function(){
    alert(element.value.length);
}, 0);
}

Beginning of a fiddle at enter link description here

Martin Smellworse
  • 1,672
  • 2
  • 25
  • 41

3 Answers3

2

Take a look at the onpaste event in javascript, you can get the clipboard text in the function you assign to the onpaste event, and process it accordingly.

To get clipboard text in the onpaste function, you can use

window.clipboardData.getData('Text')

and if the length is greater than 255 it means it has been trimmed and you can display your message to the user.

Maybe this link can help too.

JavaScript get clipboard data on paste event (Cross browser)

Community
  • 1
  • 1
  • Thank you for you reply. Unfortunately it puts a box up asking if you want to allow this web site to access your clipboard ... which is a bit of a nuisance. – Martin Smellworse Sep 10 '14 at 09:06
  • Ok, but i guess it solves you problem on how to get the length. There may be other ways on how to get the clipboard text using javascript, you can look around on those other ways, that was just one way i put there in my answer. (Y) – Hiten Naresh Vasnani Sep 10 '14 at 09:11
1

Use onpaste event in javascript

var myElement = document.getElementById('input');

myElement.onpaste = function (e) {
    if (this.value.length > 255) {
        alert("text trimmed");
    } 
    this.value = this.value.substring(0, 255); //
}

DEMO

vikrant singh
  • 2,013
  • 1
  • 10
  • 15
  • A good way to get a down vote is to answer using a library that isn't tagged or mentioned in the OP. Code–only answers aren't rated highly either. – RobG Sep 10 '14 at 08:55
1

can also use something like this binded with onchange event of javascript

<input type="text" onchange="handleLength(this)"/>

function handleLength(ele){     
            if(ele.value.length>10){
            ele.value= ele.value.substring(0,10);
            alert("your text has been trimmed");        
            }
        }
Himanshu
  • 497
  • 1
  • 3
  • 13