无法通过oop js获取输入值

时间:2017-02-21 06:40:53

标签: javascript jquery oop

您好我正在尝试使用oop js从表单输入中获取输入值。

当我获得用户名时,我想验证它,但我无法获得用户名的值。

当我在console.log(用户名)时;我得到未定义或html标记而不是值。我做错了什么?

我的表格

<form action="" method="post">
    <input type="text" name="username" id="username">
</form>

和我的js

<script type="text/javascript">
validateForm = {

    username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),

    checkUsernameValid : function() {
        $('#username').on('keyup change', function() {
            console.log(this.username);
            if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
                alert('bad')
            } else {
                alert('good');
            }
        });
    }
};

validateForm.checkUsernameValid();
</script>

2 个答案:

答案 0 :(得分:1)

generateRandomPoint(array(3.1528, 101.7038), 4); 内拨打this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, ''));this.username = $('#username').val();来设置值

&#13;
&#13;
keyup event
&#13;
validateForm = {

    username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),

    checkUsernameValid : function() {
        $('#username').on('keyup change', function() {
        this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, ''));
            console.log(this.username);
            if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
               // alert('bad')
            } else {
               // alert('good');
            }
        });
    }
};

validateForm.checkUsernameValid();
&#13;
&#13;
&#13;

答案 1 :(得分:1)

  

我要么未定义,要么 html标记而不是值。

由于您已设置了name和id属性,因此它在全局范围内可用,因此,html元素将在控制台中记录。

您不应该以这种方式绑定事件。您可以在绑定事件中调用该方法,并使该方法接受该值作为参数,例如:

validateForm = {
  username: $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
  checkUsernameValid: function(value) { // 2. get the value
    this.username = value; // 3. set the value
    if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
      console.log('bad')
    } else {
      console.log('good');
    }
  }
};
$('#username').on('keyup change', function() {
  validateForm.checkUsernameValid(this.value); // 1. pass the input value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
  <input type="text" name="username" id="username">
</form>

相关问题