Javascript 当字符少于3个时禁用HTML按钮
我目前正在与一个新闻网站合作,我想做一个搜索功能,禁用搜索按钮,直到输入有三个字符 这是我目前的密码Javascript 当字符少于3个时禁用HTML按钮,javascript,html,forms,search,button,Javascript,Html,Forms,Search,Button,我目前正在与一个新闻网站合作,我想做一个搜索功能,禁用搜索按钮,直到输入有三个字符 这是我目前的密码 <div style="margin-left: 300px; margin-top: 25px; margin-bottom: 20px;"> <form action="searchnews.php?p=0" method="POST"> <input type="text" id="searchterm" name="searchter
<div style="margin-left: 300px; margin-top: 25px; margin-bottom: 20px;">
<form action="searchnews.php?p=0" method="POST">
<input type="text" id="searchterm" name="searchterm" placeholder="Buscar Término...">
<input type="submit" id="search" value="Buscar Noticia" class="search" disabled="disabled" />
</div>
我想让它停止禁用按钮,直到第三个字符出现,而不是当第一个字符出现时,我已经尝试了一切,但没有任何效果。有什么想法吗?我非常感谢。你为什么不试试.length
if ($(this).val().length <= 3) {
empty = true;
}
if($(this).val().length在@Dim_Ch的答案中,.lengh不是函数。
你可以用这个
if ($(this).val().length <= 3) {
empty = true;
}
if($(this).val().length尝试以下方法。它有效。它还将减少函数长度
(function() {
$('input#searchterm').keyup(function() {
var enable = false;
if ($(this).val().length >= 3) {
enable = true;
}
if (enable) {
$('#search').removeAttr('disabled');
} else{
$('#search').attr('disabled','disabled');
}
});
})()
编辑:我将进一步减少:
(function() {
$('input#searchterm').keyup(function() {
$('#search').attr('disabled', $(this).val().length < 3? true : false);
});
})()
(函数(){
$('input#searchterm').keyup(函数(){
$('#search').attr('disabled',$(this).val().length<3?true:false);
});
})()
我在您的代码中没有看到编号3
这应该是一个提示。您没有结账单tag@JimGarrison,我前一段时间尝试添加3,但我的代码出错了,这是目前有效的JS…length将返回val的长度。它确实抛出了一个错误,按钮无法激活。等等,我在answ上添加了括号修复后的er+1。我将删除这些注释。检查您的代码很重要。是的,我知道有时我写得太快了,如果您要减少代码,您可以将代码减少8行。$('#search').attr('disabled',$(this).val().length<3?true:false);
(function() {
$('input#searchterm').keyup(function() {
$('#search').attr('disabled', $(this).val().length < 3? true : false);
});
})()
(function() {
$('form > input').keyup(function() {
var empty = false;
$(this).each(function() {
console.log($(this).val().length);
if ($(this).val().length >= 3) {
empty = true;
}
});
if (!empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})()