最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - validating textbox checking if it isn't readonly first - Stack Overflow

programmeradmin3浏览0评论

i have a form with two modes one that allows edit (value of text box)

and another mode for (non-manager) user - code behind adding "READONLY" to the TextBox tag.

so with the readonly 'mode' there's no input accepted in text box at all

my question is how could i execute validation method based on "READONLY" property of text box ?

strRo = "READONLY" on a condition

<asp:TextBox ID="txtNumbers" runat="server" <%=strRo %> onkeypress="return allowonlynumbers();" />

javascript function

   function allowonlynumbers() {
        if (event.keyCode >= 48 && event.keyCode <= 57) {
            return true;
            }

        else {
            alert('Only numbers can be entered');
             return false;
        }

    }

i have a form with two modes one that allows edit (value of text box)

and another mode for (non-manager) user - code behind adding "READONLY" to the TextBox tag.

so with the readonly 'mode' there's no input accepted in text box at all

my question is how could i execute validation method based on "READONLY" property of text box ?

strRo = "READONLY" on a condition

<asp:TextBox ID="txtNumbers" runat="server" <%=strRo %> onkeypress="return allowonlynumbers();" />

javascript function

   function allowonlynumbers() {
        if (event.keyCode >= 48 && event.keyCode <= 57) {
            return true;
            }

        else {
            alert('Only numbers can be entered');
             return false;
        }

    }
Share Improve this question asked Sep 24, 2012 at 16:06 LoneXcoderLoneXcoder 2,1637 gold badges40 silver badges77 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You would need to pass a reference to the element in your function call, so change the onkeypress to this:

onkeypress="return allowonlynumbers(this);"

Then, your function needs to be like this:

function allowonlynumbers(obj) {

}

And the logic you can use is:

if (obj.readOnly) {
    // The element is readonly
}

You should bind your event handler in javascript (why?). Then you will be able to use the this operator inside of the handler to refer to the textbox, which you can check the readOnly property of:

document.getElementById('test').onkeypress = function () {
    if (!this.readOnly) {
        if (event.keyCode >= 48 && event.keyCode <= 57) {
            return true;
        } else {
            alert('Only numbers can be entered');
            return false;
        }
    }
};​

http://jsfiddle/FedsQ/

发布评论

评论列表(0)

  1. 暂无评论