开发者

Problem with keyPress in Mozilla

开发者 https://www.devze.com 2022-12-26 09:22 出处:网络
I am usingtextarea to get some inputs. A label shows the updated chars left. It works fine in IE, but in FF 3.0, after reaching the max limit, it doesn\'t allow to delete 开发者_StackOverflowor backsp

I am usingtextarea to get some inputs. A label shows the updated chars left. It works fine in IE, but in FF 3.0, after reaching the max limit, it doesn't allow to delete 开发者_StackOverflowor backspace key.

I am using a javascript function on keypress event of the textarea.

the javascript code is

function checkLength()
{
    var opinion = document.getElementById('opinion').value;
    if(opinion.length > 50)
        alert("You have reached the mas limit.");
    else
        document.getElementById('limit').innerHTML = 50 - opinion.length;
}

while on the page, i am using this

<label id="limit">50 </label>
<textarea id="opTxtArea" onkeypress="javascript:checkLength();"></textarea>

Everything is working fine. The problem arises in FF, when the inputs reach the max limit, the message is displayed, but it doesn't allow to delete or backspace.


You javascript code is wrong

function checkLength()
{
    var opinion = document.getElementById('opTxtArea').value;
    if(opinion.length > 50)
        alert("You have reached the mas limit.");
    else
        document.getElementById('limit').innerHTML = 50 - opinion.length;
}

You were taking the wrong element

var opinion = document.getElementById('opinion').value;

is now changed to

var opinion = document.getElementById('opTxtArea').value;


Tried removing "javascript:"?

Javascript:

function checkLength()
{
var opinion = document.getElementById('opTxtArea').value;
if(opinion.length > 50)
    alert("You have reached the max limit.");
else
    document.getElementById('limit').innerHTML = 50 - opinion.length;
}

HTML Code:

<label id="limit">50</label>
<textarea id="opTxtArea" onkeypress="checkLength();" maxlength="50"></textarea>

In addition, at the line document.getElementById('opinion').value, I think you have the wrong ID entered.


As noted in another answer, you should remove the javascript: prefix in the onkeypress attribute, since this serves no purpose.

There are other problems here. What do you actually want to achieve? The alert is very annoying for the user, so I would suggest instead displaying an element on the page to say that the character limit has been exceeded. Also, what do you want to happen when the character limit is exceeded? You could either prevent further input (while not preventing deletion) or do what Stack Overflow does for its comment fields, which is to show a negative number when the character limit has been exceeded but not prevent further input.

0

精彩评论

暂无评论...
验证码 换一张
取 消