确定我试图在表单的输入值上运行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');
};
})
答案 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)
我将如何做到这一点:
submit
事件而不是click
事件e.preventDefault()
,因此在我准备好之前表格不会提交。
$(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;