我有这个jquery在提交注册表单之前检查用户名是否正在使用。用户名检查工作正常。但是,如果用户名不可用,我想禁用提交按钮。这是我的代码。它第一次工作:如果用户名不可用,则按钮被禁用。但是一旦用户名不可用,任何用户名之后的用户名仍然会被禁用提交按钮。如何在不刷新页面的情况下启用按钮?
<script type="text/javascript">
$(document).ready(function() {
$("#username").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
var username = $(this).val();
if(username.length < 4){$("#user-result").html('');return;}
if(username.length >= 4){
$("#user-result").html('<img src="imgs/ajax-loader.gif" />');
$.post('check_username.php', {'username':username}, function(data) {
if(data == '<img src="imgs/available.png" /> Username Available'){
$("#sumbit").attr("disabled", false);
$("#user-result").html(data);
}else{
$("#submit").attr("disabled", true);
$("#user-result").html(data);
}
});
}
});
});
</script>
check_username.php如下所示:
//sanitize username
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
//check username in db
$results = mysqli_query($connecDB,"SELECT username FROM users WHERE username='$username'");
//return count
$username_exist = mysqli_num_rows($results);
if($username_exist) {
die('<img src="imgs/not-available.png" /> Username Not Available');
}else{
die('<img src="imgs/available.png" /> Username Available');
}
html提交如下所示: html输入是
<input type="submit" id="submit" class="special" name="submit"
value="Register" />
答案 0 :(得分:1)
尝试使用以下内容删除禁用:$("#sumbit").removeAttr("disabled");
试试此代码
<script type="text/javascript">
$(document).ready(function() {
$("#username").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
var username = $(this).val();
if(username.length < 4){$("#user-result").html('');return;}
if(username.length >= 4){
$("#user-result").html('<img src="imgs/ajax-loader.gif" />');
$.post('check_username.php', {'username':username}, function(data) {
if(data == 'Available'){
$("#submit").attr("disabled", false);
$("#user-result").html('<img src="imgs/available.png" /> Username Available');
}else{
$("#submit").attr("disabled", true);
$("#user-result").html('<img src="imgs/not-available.png" /> Username Not Available');
}
});
}
});
});
</script>
check_username.php 如下所示:
//sanitize username
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
//check username in db
$results = mysqli_query($connecDB,"SELECT username FROM users WHERE username='$username'");
//return count
$username_exist = mysqli_num_rows($results);
if($username_exist) {
die('NotAvailable');
}else{
die('Available');
}
答案 1 :(得分:0)