无法获取数据并运行if语句

时间:2015-01-19 21:25:19

标签: jquery forms if-statement

确定我试图在表单的输入值上运行if语句,我希望如果用户输入这些名称,一旦单击提交if语句运行并返回控制台消息。我怎么能这样做?

var manager = 'manager';
var business = 'business';
var person = 'person';
var username = $('#uname').val();

$('submitMe').on('click', function(manager, business, person){
    if (username === manager){
    console.log('yup manager');
}else if (username === business){
    console.log('yup business');
}else if (username === person){
    console.log('yup Person');
};
})

2 个答案:

答案 0 :(得分:1)

在表单中添加ID

<form id="form1">
  Enter name: <input id="uname" type="text" >
  <input type="submit">
</form>

然后在脑袋里:

$(function() {
  $("#form1").on("submit",function(e) {
    e.preventDeafult(); // stop submission
    var manager = 'manager';
    var business = 'business';
    var person = 'person';
    var username = $('#uname').val();

    if (username === manager)
    {
       console.log('yup manager');
    }
    else if (username === business)
    {
       console.log('yup business');
    }
    else if (username === person)
    {
       console.log('yup Person');
    };
  });
});

答案 1 :(得分:0)

我将如何做到这一点:

  1. 我会使用submit事件而不是click事件
  2. 我会使用数组而不是几个变量
  3. 如果有必要,我会使用e.preventDefault(),因此在我准备好之前表格不会提交。
  4. &#13;
    &#13;
    $(document).ready(function() {
        $('#myform').on('submit', function(e) {
            e.preventDefault();
            var users = ['manager','business','person'],
                username = $('#uname').val();
            if( users.indexOf( username ) !== -1 ) {
                console.log( 'yup ' + username );
            }
        });
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <form method="POST" id="myform">
      User Name:   <input type="text" name="uname" id="uname"/>
      Password:   <input type="password" name="password id="password"/>
      <input type="submit" id="submitMe" value="Submit Me"/>
    </form>
    &#13;
    &#13;
    &#13;