如何在jQuery函数中获取asp文本框的id

时间:2012-11-19 07:34:21

标签: jquery validation

如何在被调用的函数中获取当前asp文本框的id?

<script type="text/javascript">

    $(document).ready(function () {
        $("#<%=txtNumeric.ClientID %>").focusout(function () {
            var textvalue = $("#<%=txtNumeric.ClientID %>").val();
            if (!validateDecimal(textvalue))
                return false;
            else {
                $(this).removeClass("focus");
                return true;
            }
        });
    });

    function validateDecimal(value) {
        var RE = new RegExp(/^\d\d*\.\d\d$/);
        if (RE.test(value)) {
            return true;
        } else {
            alert("Please Enter in XX.XX format !");
            $(this).addClass("focus");// this keyword is not working here !!
            $(this).focus(); // this keyword is not working here !!
            return false;
        }
    }
</script>

2 个答案:

答案 0 :(得分:0)

也在像这样的函数中传递控制对象

$(document).ready(function () {
        $("#<%=txtNumeric.ClientID %>").focusout(function () {
            var textvalue = $("#<%=txtNumeric.ClientID %>").val();
            if (!validateDecimal(textvalue,this))
                return false;
            else {
                $(this).removeClass("focus");
                return true;
            }
        });

    });

    function validateDecimal(value,ControlObject) {
            var RE = new RegExp(/^\d\d*\.\d\d$/);
            if (RE.test(value)) {
                return true;
            } else {
                alert("Please Enter in XX.XX format !");
                $(ControlObject).addClass("focus");// this keyword is not working here !!
                $(ControlObject).focus(); // this keyword is not working here !!
                return false;
            }
        }

答案 1 :(得分:0)

为什么不将它作为参数传递给validateDecimal,例如 -

function validateDecimal(value, textbox) {
    var RE = new RegExp(/^\d\d*\.\d\d$/);
    if (RE.test(value)) {
        return true;
    } else {
        alert("Please Enter in XX.XX format !");
        textbox.addClass("focus");
        textbox.focus();
        return false;
    }
}

话虽如此,我认为validateDecimal不应该有任何改变文本框的逻辑。原因是每个函数应该只做一件事,而且validateDecimal应该只进行验证并返回true / false。更改文本框类/ etc的逻辑应该在validateDecimal之外的另一个函数中。